2012-04-12 42 views
2

我遇到了CGBitmapcontext的问题。 我在创建带有“无效句柄”消息的CGBitmapContext时出现en错误。“Invalid Handle”Create CGBitmapContext

这里是我的代码:

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

谢谢;

回答

6

这是因为您将null传递给第一个参数。 CGBitmapContext用于直接绘制到内存缓冲区中。在构造的所有的重载第一个参数是(苹果文档):

数据 一个指针,指向存储器中的目的地,其中该图是要被渲染。此内存块的大小应至少为 (bytesPerRow * height)个字节。

在MonoTouch中,为了方便起见,我们得到两个接受字节[]的重载。所以,你应该用这样的:

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); 
+0

值谢谢非常mutch;)这个工作对我来说) – Alex 2012-04-13 06:21:43

+0

谢谢,虽然这种行为是不同的苹果文档说:'数据',如果非NULL,指向内存块至少'bytesPerRow *高度'字节 。如果'data'为NULL,则上下文数据 将自动分配,并在上下文取消分配 时释放。 – Hrissan 2013-06-09 19:15:14

+0

重要的一点!如果您在停止使用上下文之前允许您的ctxBuffer被垃圾收集,您的应用程序将随机崩溃!我在类级别上有上下文变量,而ctxBuffer在函数创建上下文中是局部变量。应用程序崩溃,直到我将ctxBuffer移动到类级别。谨防! – Hrissan 2013-06-09 20:39:54

0

这也有可能发生,如果widthheight参数传递到方法都为0