Android:创建的位图颜色错误

时间:2015-10-14 21:45:50

标签: android bitmap

我将ios app移植到android并且在从字节数组创建时遇到位图颜色问题。此代码完美适用于ios(C# - Xamarin):

const int bitsPerComponent = 8;
const int bytePerPixel = 4;
var bytesPerRow = bytePerPixel * BarcodeImageWidth;
var colorSpace = CGColorSpace.CreateDeviceRGB();

var context = new CGBitmapContext(byteArray,
    BarcodeImageWidth, BarcodeImageHeight,
    bitsPerComponent, bytesPerRow,
    colorSpace, CGImageAlphaInfo.NoneSkipFirst);

BarcodeImageView.Image = new UIImage(context.ToImage());

ios

Android上的这段代码使位图的颜色错误:

var bitmap = Bitmap.CreateBitmap(barcode.Width, barcode.Height, Bitmap.Config.Argb8888);
bitmap.CopyPixelsFromBuffer(ByteBuffer.Wrap(imageBytes));
barcode.SetImageBitmap(bitmap);

android

1 个答案:

答案 0 :(得分:0)

修正了手动创建的像素数组,跳过了第一个(alpha)字节。

int pixelsCount = imageBytes.Length / 4;
int[] pixels = new int[pixelsCount];
for (int i = 0; i < pixelsCount; i++)
{
    var offset = 4 * i;
    int r = imageBytes[offset + 1];
    int g = imageBytes[offset + 2];
    int b = imageBytes[offset + 3];
    pixels[i] = Color.Rgb(r, g, b);
}

var bitmap = Bitmap.CreateBitmap(pixels, barcode.Width, barcode.Height, Bitmap.Config.Argb8888);
barcode.SetImageBitmap(bitmap);