UIGraphicsBeginImageContext创建的图像永远留在内存中

时间:2013-06-23 17:47:13

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

我正在使用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;
}

1 个答案:

答案 0 :(得分:0)

添加到verticallyFlipImagetempImageView.image = nil;,以使图片视图释放图片。这解决了这个问题。