Iphone 在CGImageRef和UIImage之间共享内存

Iphone 在CGImageRef和UIImage之间共享内存,iphone,memory,uiimage,Iphone,Memory,Uiimage,有没有办法从屏幕外表面创建UIImage对象而不复制底层像素数据 我想这样做: // These numbers are made up obviously... CGContextRef offscreenContext = MyCreateBitmapContext(width, height); // Draw into the offscreen buffer // Draw commands not relevant... // Convert offscreen into CGI

有没有办法从屏幕外表面创建UIImage对象而不复制底层像素数据

我想这样做:

// These numbers are made up obviously...
CGContextRef offscreenContext = MyCreateBitmapContext(width, height);

// Draw into the offscreen buffer
// Draw commands not relevant...

// Convert offscreen into CGImage
// This consumes ~15MB
CGImageRef offscreenContextImage = CGBitmapContextCreateImage(offscreenContext);

// This allocates another ~15MB
// Is there any way to share the bits from the 
// CGImageRef instead of copying the data???
UIImage * newImage = [[UIImage alloc] initWithCGImage:offscreenContextImage];

// Releases the original 15MB, but the spike of 30MB total kills the app.
CGImageRelease(offscreenContextImage);
CGContextRelease(offscreenContext);
内存被释放,并在可接受的大小上保持稳定,但30MB的内存峰值会导致应用程序死机。有没有办法共享像素数据

我曾考虑将屏幕外的缓冲区保存到一个文件中,然后再次加载数据,但这是一个黑客行为,iPhone的便捷方法需要一个UIImage来保存它……

也许吧

UIImage *newImage = [[UIImage alloc[ initWithData:offScreenContext];
也许吧


您可以在创建CGImage之后立即释放上下文,释放上下文使用的内存,因为CGBitmapContextCreateImage()创建上下文的副本

像这样:

CGImageRef offscreenContextImage = CGBitmapContextCreateImage(offscreenContext);

CGContextRelease(offscreenContext);

UIImage * newImage = [[UIImage alloc] initWithCGImage:offscreenContextImage];

// ...

CGImageRelease(offscreenContextImage);

您可以在创建CGImage之后立即释放上下文,释放上下文使用的内存,因为CGBitmapContextCreateImage()创建上下文的副本

像这样:

CGImageRef offscreenContextImage = CGBitmapContextCreateImage(offscreenContext);

CGContextRelease(offscreenContext);

UIImage * newImage = [[UIImage alloc] initWithCGImage:offscreenContextImage];

// ...

CGImageRelease(offscreenContextImage);

UIImage:initWithData采用NSData*参数,我还没有找到从CGImageRef或CGContextRef获取NSData*的方法。NSData采用JPEG和PNG等图像格式,您可以通过initWithData重新输入这些格式-另一种方法是,通过PNGRepresentation和JPGRepresentation调用从UIImage中获取NSData*块。因此,它对您没有帮助。UIImage:initWithData采用NSData*参数,我还没有看到从CGImageRef或CGContextRef获取NSData*的方法。NSData采用JPEG和PNG等图像格式,您可以通过initWithData重新输入这些格式,反之亦然,您可以通过PNGRepresentation和JPGRepresentation调用从UIImage中获取NSData*块。因此,这对您没有帮助。CGBitmapContextCreateImage调用是分配大块内存的方法。在那里发布任何内容都不会影响UIImage的初始化。这不是正确的答案。所以我尝试了别的方法。我以前的所有结果都是使用3.0 SDK的。我使用3.1 SDK编译,我的分配从15MB的稳定状态(峰值为30MB)变为2MB的稳定状态(峰值为6MB)。难以置信的我回去清理了两个版本,以确保数据正确无误。ObjectAlloc显示了相同的结果。看起来3.1 SDK修复了一些内存问题。CGBitmapContextCreateImage调用是分配大块内存的方法。在那里发布任何内容都不会影响UIImage的初始化。这不是正确的答案。所以我尝试了别的方法。我以前的所有结果都是使用3.0 SDK的。我使用3.1 SDK编译,我的分配从15MB的稳定状态(峰值为30MB)变为2MB的稳定状态(峰值为6MB)。难以置信的我回去清理了两个版本,以确保数据正确无误。ObjectAlloc显示了相同的结果。看起来3.1 SDK修复了一些内存问题。