xamarin.ioscgbitmapcontext

Invalid parameters in CGBitmapContext constructor


I'm trying to create a blank bitmap in a Xamarin.iOS project using the CGBitmapContext constructor(s). However, no matter what I try I just get the error "System.Exception: Invalid parameters to context creation"

Example code:

const int width = 100;
const int height = 100;
const int bytesPerPixel = 4;
const int bitsPerComponent = 8;
var intBytes = width * height * bytesPerPixel;
byte[] pixelData = new byte[intBytes];
var colourSpace = CGColorSpace.CreateDeviceRGB();
using (var objContext = new CGBitmapContext(pixelData, width, height, bitsPerComponent, width * bytesPerPixel, colourSpace, CGBitmapFlags.ByteOrderDefault))
{
    // ...
}

I have tried changing most of the parameters; I tried fixing the data block and passing it as an IntPtr. I tried using null as the first parameter so that the system would allocate the data. And I've tried various flags in the last parameter. I always get that same error. What parameter is wrong? And what needs to be changed in the code above to make it execute?


Solution

  • I changed last parameter from CGBitmapFlags.ByteOrderDefault to CGBitmapFlags.PremultipliedLast , and the error disappear.

    refer to CGBitmapFlags Enumeration

    As the link said

    This enumeration specifies the layout information for the component data in a bitmap.

    This enumeration determines the in-memory organization of the data and includes the color model, whether there is an alpha channel present and whether the component values have been premultiplied.

    I think we have to select the corresponding flag to match the data info, especially the color model.

    For the same reason, If you choose CreateDeviceCmyk , CGBitmapFlags.None will be appropriate.