【问题标题】:UIGraphicsBeginImageContext created image stays in memory foreverUIGraphicsBeginImageContext 创建的图像永远留在内存中
【发布时间】:2013-06-23 17:47:13
【问题描述】:

我正在使用 Core Graphics 创建图像的许多颜色变化。我总共需要创建大约 320 个,但逐渐地,应用程序的内存使用量不断增加,直到它崩溃。从 Instruments 中,我看到正在创建更多 CGImage 对象并保持活力。我想发布它们,因为我将图像以 PNG 格式存储到缓存目录中。

我已经搜索了所有其他我能找到但没有成功的解决方案。任何帮助表示赞赏。谢谢。

这里是主要部分:

+(UIImage *)tintedImageFromImage:(UIImage *)sourceImage colour:(UIColor *)color intensity:(float)intensity {

    if (UIGraphicsBeginImageContextWithOptions != NULL) {

        UIGraphicsBeginImageContextWithOptions(sourceImage.size, NO, 0.0);

    } else {

        UIGraphicsBeginImageContext(sourceImage.size);
    }

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(0, 0, sourceImage.size.width, sourceImage.size.height);

    // draw alpha-mask
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGContextDrawImage(context, rect, sourceImage.CGImage);

    // draw tint color, preserving alpha values of original image
    CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    [color setFill];
    CGContextFillRect(context, rect);


    //Set the original greyscale template as the overlay of the new image
    sourceImage = [self verticallyFlipImage:sourceImage];
    [sourceImage drawInRect:CGRectMake(0,0, sourceImage.size.width,sourceImage.size.height) blendMode:kCGBlendModeMultiply alpha:intensity];

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

    colouredImage = [self verticallyFlipImage:colouredImage];


    return colouredImage;
}

这是用来翻转图像的:

+(UIImage *)verticallyFlipImage:(UIImage *)originalImage {

    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:originalImage];

    UIGraphicsBeginImageContext(tempImageView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, tempImageView.frame.size.height);

    CGContextConcatCTM(context, flipVertical);

    [tempImageView.layer renderInContext:context];

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

    return flippedImage;
}

【问题讨论】:

    标签: memory-leaks uiimage core-graphics cgcontext cgimage


    【解决方案1】:

    tempImageView.image = nil; 添加到verticallyFlipImage 行,以使图像视图释放图像。这样就解决了问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      相关资源
      最近更新 更多