2

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;

Alex
  • 459
  • 3
  • 14

2 Answers2

6

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);
Dimitris Tavlikos
  • 8,170
  • 1
  • 27
  • 31
  • Thanks, though this behavior is different to what apple docs say: `data', if non-NULL, points to a block of memory at least `bytesPerRow * height' bytes. If `data' is NULL, the data for context is allocated automatically and freed when the context is deallocated. – Hrissan Jun 09 '13 at 19:15
  • Important point! Your app will crash randomly if you allow your ctxBuffer to be garbage collected before you stop using context! I had context variable on class level, while ctxBuffer was local variable in the function creating context. App was crashing until I moved ctxBuffer to class level. Beware! – Hrissan Jun 09 '13 at 20:39
0

This can also happen if the width or height parameters passed into the method have a value of 0.

chkimes
  • 1,127
  • 13
  • 20