Core Graphics图像混合不会释放内存

时间:2014-07-31 07:16:46

标签: ios objective-c memory-management core-graphics

我正在使用以下代码混合两个图像:

+ (UIImage *)xxx_blendedImageWithFirstImage:(UIImage *)image
                                secondImage:(UIImage *)secondImage
                            renderedInFrame:(CGRect)frame
                                      alpha:(CGFloat)alpha {
    UIGraphicsBeginImageContextWithOptions(frame.size, NO, UIScreen.mainScreen.scale);

    [image drawInRect:frame];
    [secondImage drawInRect:frame blendMode:kCGBlendModeNormal alpha:alpha];

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

    return newImage;
}

此代码在IBAction中为UISlider调用,以便在每个滑块位置更改时调用它。这是此代码的内存占用量:

Memory footprint

它需要230 MB然后由于内存压力而失败。

如何使此代码正常工作?

2 个答案:

答案 0 :(得分:0)

如果您已将此IBAction与xib中的Value Changed事件相关联,请在后台线程上执行此操作。 Make sure do all UI changes on main thread

否则将此IBAction与Touch Up Inside事件相关联。此方法将调用,当您在一次拖动中离开滑块一次。 (不适用于所有拖动值)

希望它能解决你的问题

答案 1 :(得分:0)

添加@autoreleasepool后:

+ (UIImage *)xxx_blendedImageWithFirstImage:(UIImage *)image
                                secondImage:(UIImage *)secondImage
                            renderedInFrame:(CGRect)frame
                                      alpha:(CGFloat)alpha {
    UIImage *newImage = nil;
    @autoreleasepool {
        UIGraphicsBeginImageContextWithOptions(frame.size, NO, UIScreen.mainScreen.scale);

        [image drawInRect:frame];
        [secondImage drawInRect:frame blendMode:kCGBlendModeNormal alpha:alpha];

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

也许,应该有一些手动版本,但现在内存占用情况如下: enter image description here