从位图设置图像

Kir*_*ill 5 c# android xamarin xamarin.forms

Image image = new Image ();
Bitmap bitmap = Bitmap.CreateBitmap (200, 100, Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(bitmap);

var paint = new Paint();
paint.Color = Android.Graphics.Color.Red;
paint.SetStyle(Paint.Style.Fill);

Rect rect = new Rect(0, 0, 200, 100);
canvas.DrawRect(rect, paint);
Run Code Online (Sandbox Code Playgroud)

Android.Widget.ImageView包含方法SetImageBitmap。从我的位图
设置Xamarin.Forms.Image的最佳方法是什么?

Wos*_*osi 2

通过http://forums.xamarin.com/discussion/5950/how-to-convert-from-bitmap-to-byte-without-bitmap-compress转换Bitmapbyte[]

提到了两种解决方案。

  1. var byteArray = ByteBuffer.Allocate(bitmap.ByteCount);
    bitmap.CopyPixelsToBuffer(byteArray);
    byte[] bytes = byteArray.ToArray<byte>();
    return bytes;
    
    Run Code Online (Sandbox Code Playgroud)
  2. (如果第一个解决方案仍然损坏)

    ByteBuffer buffer = ByteBuffer.Allocate(bitmap.ByteCount);
    bitmap.CopyPixelsToBuffer(buffer);
    buffer.Rewind();
    
    IntPtr classHandle = JNIEnv.FindClass("java/nio/ByteBuffer");
    IntPtr methodId = JNIEnv.GetMethodID(classHandle, "array", "()[B");
    IntPtr resultHandle = JNIEnv.CallObjectMethod(buffer.Handle, methodId);
    byte[] byteArray = JNIEnv.GetArray<byte>(resultHandle);
    JNIEnv.DeleteLocalRef(resultHandle);
    
    Run Code Online (Sandbox Code Playgroud)

然后使用

var image = new Image();
image.Source = ImageSource.FromStream(() => new MemoryStream(byteArray));
Run Code Online (Sandbox Code Playgroud)

创建一个Image.

  • 第一个解决方案有例外,第二个解决方案 - image.Width == -1 (也不起作用) (2认同)