如何使用Xamarin将嵌入式资源加载到Android位图中?

问题描述 投票:3回答:4

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

在iOS上我可以简单地使用

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

加载嵌入的图像并在UIImageView或类似的中使用它。如何在Android特定代码中完成相同的操作?

android bitmap xamarin embedded-resource xamarin.forms
4个回答
0
投票

不完全干净和测试,但您可能想要创建ImageLoaderSourceHandler类的实例并调用其LoadImageAsync方法,向其传递ImageSource,context和CancellationToken(可选)的实例。你最终会得到一个Android.Graphics.Bitmap的实例。

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


1
投票

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

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

0
投票

这就是我这样做的方式:

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

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


0
投票

这可能对你有用。

// 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);
}
© www.soinside.com 2019 - 2024. All rights reserved.