Xamarin: 如何从iOS库项目加载图片

9

我有一个使用MvvmCross样式化的Xamarin项目。这里有以下子项目:

  • 核心 (PCL)
  • 视图模型 (PCL)
  • iOS (可执行文件)

如果我在我的iOS项目中添加一个图片(Resoureces/Images/test_image.png),那么我可以用下面的代码来加载它:

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

现在,我想使用一个新的子项目

  • 控件(iOS库)

这个库应该加载一张图片。我已经将一张图片添加到控件中(资源/图像/测试图片.png)

但是我无法在控件项目中加载这个图片。

我的问题:如何从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)); 
        }
    }

这里输入图片描述

这是完整的项目:https://bitbucket.org/ww_wschaefer/xamarin-first-crossover-app/overview


1
除非作为捆绑资源可用,否则无法使用Bundle,我认为最好使用UIImage.FromFile("Images/test_icon.png")。您还应该查看此问题 - Rohit Vipin Mathews
1
我简直不敢相信,解决方案如此简单,谢谢Rohit。 - iOSfleer
很高兴你的问题已经解决。如果你感兴趣,我已经添加了解释。 - Rohit Vipin Mathews
如果您不介意的话,请接受答案,如果它解决了您的问题,这对其他人也会有帮助。@iOSfleer - Rohit Vipin Mathews
1个回答

10

关于我的评论,我稍作解释。

你必须进行更改。

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

由于图像未作为捆绑资源添加,因此无法使用UIImage.FromBundle()方法加载图像。

UIImage.FromFile()方法会异步地加载图像,它还允许应用程序从外部位置加载图像

UIImage.FromFile()方法不同,UIImage.FromBundle()方法是一个阻塞调用,仅从应用程序捆绑包中加载图像。然而,它在加载后会缓存这些图片。

如需进一步了解,请参阅书籍-使用MonoTouch开发iPhone和iPad的C#应用程序


1
@iOSfleer - 你能否确认这是否是对你有效的解决方案? - Rohit Vipin Mathews

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接