【问题标题】:How to load embedded resource into an Android Bitmap with Xamarin?如何使用 Xamarin 将嵌入式资源加载到 Android 位图中?
【发布时间】:2019-03-31 19:21:16
【问题描述】:

我正在开发一个 Xamarin.Forms 应用程序,该应用程序使用 embedded images feature 管理共享项目中的一些资产。现在我有平台特定的渲染器,它们也需要访问这些图像。

在 iOS 上我可以简单地使用

UIImage.FromResource(typeof(CustomMap).Assembly, "my_graphic");

加载嵌入的图像并在 UIImageView 或类似中使用它。如何在 Android 特定代码中实现相同的功能?

【问题讨论】:

    标签: android bitmap xamarin embedded-resource xamarin.forms


    【解决方案1】:

    这就是我的做法:

    var key = "my_graphic";
    using (var imageStream = Assembly.GetAssembly (typeof(YOURNAMESPACE.App)).GetManifestResourceStream (key))
                    {
                       var bitmap = await BitmapFactory.DecodeStreamAsync (imageStream);
                    }
    

    我的嵌入图像在 XamarinForms 项目 (PCL) 中

    【讨论】:

      【解决方案2】:

      并非完全干净且经过测试,但您可能希望创建 ImageLoaderSourceHandler 类的实例并调用其 LoadImageAsync 方法,向其传递 ImageSource、上下文和 CancellationToken(可选)的实例。 您最终会得到一个 Android.Graphics.Bitmap 实例。

      或者,如果您想绕过表单,您可能希望在 Android 项目中创建指向这些图像的链接并正常使用它们。或者加载一个byte stream from embedded resource

      【讨论】:

      【解决方案3】:

      在 droid 渲染器中,您可以像这样将图像设置为 Imageview。在使用平台特定代码时,使用平台文件结构中的图像。在 android 中将您的图像包含在 Drawable 文件夹中。

              global::Android.Widget.ImageView imageview = new global::Android.Widget.ImageView ();
              imageview.SetBackgroundResource (Resource.Drawable.my_graphic);
      

      【讨论】:

      • 我问的是在 Android 上使用嵌入式资源,而不是 Android 资源机制。
      【解决方案4】:

      这可能对你有用。

      // If your class is inherited from activity or android context then use this.
      var imageSource = ImageSource.FromFile("Images/waterfront.jpg");
      var img = new ImageLoaderSourceHandler().LoadImageAsync(imageSource,this);
      

      // if your class is not from android context then use this.
      var imageSource = ImageSource.FromFile("Images/waterfront.jpg");
      var img = new ImageLoaderSourceHandler().LoadImageAsync(imageSource,Android.App.Application.Context);
      

      这里是完整的实现

      private async Bitmap GetBitMap(path)
      {
         var imageSource = ImageSource.FromFile(path);
         return await new ImageLoaderSourceHandler().LoadImageAsync(imageSource,Android.App.Application.Context);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-11
        • 1970-01-01
        • 1970-01-01
        • 2012-03-02
        • 2016-06-26
        • 2013-05-19
        • 2011-04-11
        相关资源
        最近更新 更多