如何在Xamarin中获得可绘制文件夹内的图像作为字节数组或位图



我试图得到一个图像,"stupidshit.png",这是在我的android项目的可绘制文件夹作为字节数组或位图在一个contentpage后面的代码。我什么都试过了。什么都不行

我有一个ContentPage和ContentPage有一个按钮。当我点击

我想要这张照片以备以后使用。

你可以使用DependencyService来实现这个功能。

请参考以下代码:

1。创建一个接口,格式为:

public interface InGetImageService
{
Bitmap GetBitmap();
}

2。在android中实现接口:

[assembly: Dependency(typeof(GetImageService))]
namespace DependencyServiceDemos.Droid
{
public class GetImageService : InGetImageService
{
public Bitmap GetBitmap()
{
string imagefileName = "water.png";
// Remove the file extention from the image filename
imagefileName = imagefileName.Replace(".jpg", "").Replace(".png", "");
// Retrieving the local Resource ID from the name
int id = (int)typeof(Resource.Drawable).GetField(imagefileName).GetValue(null);
// Converting Drawable Resource to Bitmap
var originalImage = BitmapFactory.DecodeResource(MainActivity.Instance.Resources, id);
return originalImage;
}
}
}

3。点击ContentPage中的按钮时调用以下代码:

Bitmap bitmap =   DependencyService.Get<InGetImageService>().GetBitmap();

注意:

MainActivity.Instance是android中MainActivity中的一个变量,请参考以下代码:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
internal static MainActivity Instance { get; private set; }
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Instance = this;// assign a value
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
}

最新更新