2015-09-14 8 views
6

私はMvvmCrossでスタイリングされたXamarinプロジェクトを持っています。サブプロジェクトがあります。Xamarin:iOSライブラリプロジェクトから画像をロードするには

  • コア(PCL)
  • ViewModelに(PCL)
  • のiOS(実行)

私は私のiOSプロジェクト(Resoureces /画像/ test_imageに画像を追加する場合。 PNG)は、その後、私はこのコードでそれを読み込むことができます:私は新しいサブプロジェクトを使用したい、今すぐ

UIImage image = UIImage.FromBundle("Images/test_icon.png"); 

  • コントロール(iOSのライブラリ)

このライブラリには、イメージをロードする必要があります。コントロールに画像を追加しました(Resoureces/Images/test_image.png)

しかし、この画像をコントロールprojに読み込むことができません。

質問:iOSライブラリから画像を読み込むにはどうすればよいですか?

public class MyButton : UIButton 
    { 
     public MyButton() : base() 
     { 
      Initialize(); 
     } 

     void Initialize() 
     { 
      // load image from bundle 
      UIImage image = UIImage.FromBundle("Images/test_icon.png"); 
      // image is null 
      this.SetImage (image, UIControlState.Normal); 
     } 
    } 

とのViewControllerクラスです:

ここ
public partial class FirstView : MvxViewController 
    { 
     public FirstView() : base ("FirstView", null) 
     { 
     } 

     public override void ViewDidLoad() 
     { 
      base.ViewDidLoad(); 

      // load image from bundle 
//   UIImage image = UIImage.FromBundle("Images/test_icon.png"); 
//   image is not null if added in iOS Proj 
//   this.imageView.Image = image; 

      MyButton button = new MyButton(); 

      View.Add (button); 

      View.AddConstraint (NSLayoutConstraint.Create (button, NSLayoutAttribute.Right, NSLayoutRelation.Equal, View, NSLayoutAttribute.Right, 1, 10)); 
      View.AddConstraint (NSLayoutConstraint.Create (button, NSLayoutAttribute.Top, NSLayoutRelation.Equal, View, NSLayoutAttribute.Top, 1, 74)); 
      View.AddConstraint (NSLayoutConstraint.Create (button, NSLayoutAttribute.Width, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 0, 64)); 
      View.AddConstraint (NSLayoutConstraint.Create (button, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 0, 64)); 
     } 
    } 

enter image description here

いっぱいPROJです:私のコメントhttps://bitbucket.org/ww_wschaefer/xamarin-first-crossover-app/overview

+1

は、私はあなたが 'UIImage.FromFile(「画像/ test_icon.png」を使用してのより良いことだと思います) '。また、この[質問](http://stackoverflow.com/q/18130779/1155650)を見てください。 –

+1

私は信じられない、ソリューションはとても簡単です、ありがとうRohit。 – iOSfleer

+0

あなたの問題が解決してうれしいです。興味があれば説明を追加しました。 –

答えて

8

少し説明。

あなたは画像がバンドルされたリソースとして追加されていないとして

UIImage image = UIImage.FromFile("Images/test_icon.png"); 

UIImage image = UIImage.FromBundle("Images/test_icon.png"); 

を変更する必要があります。

UIImage.FromFile()メソッドは、イメージを非同期に読み込みます。 これはまた、アプリケーションが外部ロケーションからイメージをロードすることを可能にします。 UIImage.FromFile()方法とは異なり

は、UIImage.FromBundle()方法は、ブロッキング呼び出しであり、は、アプリケーションバンドル内から画像をロードします。ただし、イメージを読み込んだ後にイメージをキャッシュします。さらに理解するために

は本を見て - Developing C# Apps for iPhone and iPad using MonoTouch

あなたは、その利用可能でない限りbundeledリソースとしてバンドルから使用カント
+0

@iOSfleer - これがあなたにとってうまくいくソリューションであるかどうか確認してください。 –

関連する問題