xamarin.ioscgbitmapcontext

"Invalid Handle" Create CGBitmapContext


I've got a problem with the CGBitmapcontext. I get en error while creating the CGBitmapContext with the message "invalid Handle".

Here is my code:

var previewContext = new CGBitmapContext(null, (int)ExportedImage.Size.Width, (int)ExportedImage.Size.Height, 8, (int)ExportedImage.Size.Height * 4,                                                    CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst);

Thank you;


Solution

  • That is because you are passing null to the first parameter. The CGBitmapContext is for drawing directly into a memory buffer. The first parameter in all the overloads of the constructor is (Apple docs):

    data A pointer to the destination in memory where the drawing is to be rendered. The size of this memory block should be at least (bytesPerRow*height) bytes.

    In MonoTouch, we get two overloads that accept a byte[] for convenience. So you should use it like this:

    int bytesPerRow = (int)ExportedImage.Size.Width * 4; // note that bytes per row should 
        //be based on width, not height.
    byte[] ctxBuffer = new byte[bytesPerRow * (int)ExportedImage.Size.Height];
    var previewContext = 
        new CGBitmapContext(ctxBuffer, (int)ExportedImage.Size.Width, 
        (int)ExportedImage.Size.Height, 8, bytesPerRow, colorSpace, bitmapFlags);