iphone - 具有大图像尺寸的 UIImage - 内存问题 - 崩溃

标签 iphone crash uiimage memory-management

我想加载并显示大尺寸的图像(.jpg,.png),例如1800x1200 或 2000x1800(宽 x 高)。 如果我在 UIImageView 中显示如此大尺寸的图像(1800x1200 或 2000x1800),它也会消耗大量内存,并且应用程序会崩溃。 另外,根据 Apple 的文档 ( http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIImage_Class/Reference/Reference.html ),我们应该避免创建尺寸大于 1024 x 1024 的 UIImage 对象。 一种解决方案是调整图像大小。我已使用以下代码应用逻辑来调整图像大小。

UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

这工作正常并调整图像大小。但是,当它在设备上下文中加载大图像以调整大小时,它会在一秒钟内消耗大量内存,并且因此应用程序崩溃。 所以这个方法是行不通的。如果您有更好的方法来调整大小而不使其崩溃,请分享。

同样在此 (http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIImage_Class/Reference/Reference.html) 链接中,Apple 表示

"You should avoid creating UIImage objects that are greater than 1024 x 1024 in size. Besides the large amount of memory such an image would consume, you may run into problems when using the image as a texture in OpenGL ES or when drawing the image to a view or layer. This size restriction does not apply if you are performing code-based manipulations, such as resizing an image larger than 1024 x 1024 pixels by drawing it to a bitmap-backed graphics context. In fact, you may need to resize an image in this manner (or break it into several smaller images) in order to draw it to one of your views.". 

有人可以详细说明“如果您执行基于代码的操作,例如通过将图像绘制到位图支持的图形上下文来调整大于 1024 x 1024 像素的图像大小,则此大小限制不适用。” ?如何在位图支持的图形上下文上绘制图像?什么是位图支持的图形上下文?如果有人可以分享示例代码,这会对我有帮助。 提前致谢!!

最佳答案

UIGraphicsBeginImageContext() 创建一个位图支持的图形上下文(在幕后它调用 CGBitmapContextCreate)。

发生“限制”是因为 UIViews 是使用 CALayers 渲染的,而 CALayers 在 GPU 上渲染为纹理多边形,并且 GPU 具有最大纹理大小(在 iPhone 2G/3G 上似乎是 2044 像素,大概在 iPod Touch 上) 1G/2G)。他们在 3GS 及更高版本的设备上增加了它,大概是因为相机的图片更大。

也就是说,您应该能够毫无问题地操作单个相机大小的图像;崩溃表明您在其他地方使用了大量内存(可能是内存泄漏?)。

关于iphone - 具有大图像尺寸的 UIImage - 内存问题 - 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3440864/

相关文章:

iphone - 我想使用委托(delegate)创建 UITabbarController,UINavigationController

javascript - Node.js 堆内存不足

c - 没有编译错误,但给定输入时崩溃

iphone - 您在iPhone/iPad上推荐什么SQLite库?

iphone - OpenGL ES 中的金属闪光效果?

iphone - iPhone 3.0 上的 UIColor 限制或错误

iphone - 应用程序在 iPhone 5 6.1.4 上崩溃,但在其他版本上运行良好

ios - swift 3 : Create UIImage from UIBezierPath

ios - 如何将 Swift 中的文本格式设置为底部?

ios - OpenCV 代码导致 UIImages 泄漏