基本上,我这样做:
- (UIImage *)addPreviewImageToImage:(UIImage *)backImage
{
UIImage *newImage;
NSString *file = [[NSBundle mainBundle] pathForResource:@"sampleImage" ofType:@"png"];
UIImage *frontImage = [UIImage imageWithContentsOfFile:file];
float scale = 1.0f;
CGRect rectBack = CGRectMake(0, 0, scale * backImage.size.width, scale * backImage.size.height);
CGRect rectFront = [self rectForFrontElementOfSize:frontImage.size overElementOfSize:rectBack.size mediaType:kMediaTypeImage];
// Begin context
UIGraphicsBeginImageContextWithOptions(rectBack.size, YES, 0); // opaque = YES
// draw images
@autoreleasepool { // no effect
[backImage drawInRect:rectBack]; // where the crash occurs, backImage is about 4 Mo
}
[frontImage drawInRect:rectFront];
// grab context
newImage = UIGraphicsGetImageFromCurrentImageContext();
// end context
UIGraphicsEndImageContext();
return newImage;
}
这在 iPhone 5 或更高版本 (iOS7) 上运行良好,但在 drawInRect: 调用的 4S 上 80% 的时间崩溃。如何优化此代码?将 backImage 写入磁盘然后通过 contentsOfFile 获取它会更有效吗?有任何想法吗 ?
编辑(崩溃详细信息):收到内存警告后,Xcode 终止应用程序,说明:
“因内存压力而终止”
通过使用断点,我知道在执行 drawInRect:backImage (这是来自相机的图片)时会发生这种情况
崩溃前的rectBack描述:
(CGRect) rectBack = 原点=(x=0, y=0) 大小=(宽度=2448, 高度=3264)
注意:在 UIGraphicsBeginImageContextWithOptions 中将 opaque 参数设置为 YES 并减少 scale 参数似乎可以使其工作,但我正在失去质量,我想知道逻辑是否有问题