OGeek|极客世界-中国程序员成长平台

标题: ios - CG 栅格数据对于一张图像来说太大了 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:33
标题: ios - CG 栅格数据对于一张图像来说太大了

我试图旋转用相机拍摄的 2448x3264 的 UIImage。当我这样做时,内存大约达到 120Mb,大约持续 3/4 秒,然后恢复到正常状态。问题是,在内存较少的设备(例如,ipod touch)中,应用程序崩溃。即使没有,我认为它不应该为一张图像使用那么多内存。发生这种情况时,Iphone 5 也会滞后。

根据 this 中的评论回答,使用 UIGraphicsGetCurrentContext() 后解压内存的字节大小应该是 width * height * CGImageGetBitsPerComponent(image.CGImage)/8 bytes,所以图片应该占用 8Mb,而不是 120。

知道为什么会发生这种情况以及如何解决吗?

这是返回旋转图像的 UIImage 分类方法:

- (UIImage *)imageRotatedByDegreesCGFloat)degrees {
    CGFloat radian = (CGFloat) (degrees * (M_PI/ 180.0f));
    CGSize rotatedSize = [self rotatedImageSize:degrees];

    // Create the bitmap context
    UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, 0);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();

    CGPoint contextCenter = CGPointMake(rotatedSize.width/2.0f, 
rotatedSize.height/2.0f);
    CGContextTranslateCTM(bitmap, contextCenter.x, contextCenter.y);

    //   // Rotate the image context
    CGContextRotateCTM(bitmap, radian);
    // Now, draw the rotated/scaled image into the context
    [self drawInRect:CGRectMake(-self.size.width/2.0f, -
self.size.height/2.0f, self.size.width, self.size.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

这是来自仪器的证明,即在执行旋转方法时,栅格数据是导致内存峰值的原因:

Instruments proof



Best Answer-推荐答案


几点说明:

关于ios - CG 栅格数据对于一张图像来说太大了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43594513/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4