【问题标题】:Core Graphics image blending doesn't release memoryCore Graphics 图像混合不会释放内存
【发布时间】:2014-07-31 07:16:45
【问题描述】:

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

+ (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,以便在每次滑块位置更改时调用它。这是这段代码的内存占用:

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

如何让这段代码正常工作?

【问题讨论】:

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


    【解决方案1】:

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

    否则将此 IBAction 与 Touch Up Inside 事件连接。之后这个方法会被调用,当你离开滑块的时候一拖再拖。 (不适用于所有拖动值)

    希望它能解决你的问题

    【讨论】:

    • 在 iOS 4 及更高版本中,您可以从应用程序的任何线程调用此函数。 Reference
    • @pawan 是的,它正在主线程上工作,但问题在于内存
    【解决方案2】:

    添加@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;
    }
    

    也许,应该有一些手动释放,但是现在内存占用看起来像:

    【讨论】:

      猜你喜欢
      • 2012-04-14
      • 2013-11-14
      • 2013-05-10
      • 2012-04-02
      • 2015-06-21
      • 1970-01-01
      • 2011-12-27
      • 2014-11-17
      • 1970-01-01
      相关资源
      最近更新 更多