合并两个图像并获得一个图像,但由于内存压力,应用程序崩溃

时间:2014-04-18 05:35:12

标签: objective-c image-processing ios7 uiimageview mask

由于内存压力,我的应用程序崩溃了。

在我的应用程序中,我已经合并了两个图像并获得一个图像,并使用此代码在UIImageView中设置此图像。

+ (UIImage*)imageByCombiningImages:(UIImage*)firstImage withImage:(UIImage*)secondImage
{
    @autoreleasepool
    {
        UIImage *image = nil;

        CGSize newImageSize = CGSizeMake(MAX(firstImage.size.width, secondImage.size.width), MAX(firstImage.size.height, secondImage.size.height));
        if (UIGraphicsBeginImageContextWithOptions != NULL)
        {
            UIGraphicsBeginImageContextWithOptions(newImageSize, NO, [[UIScreen mainScreen] scale]);
        }
        else
        {
            UIGraphicsBeginImageContext(newImageSize);
        }

        [firstImage drawAtPoint:CGPointMake(roundf((newImageSize.width-firstImage.size.width)/2), roundf((newImageSize.height-firstImage.size.height)/2))];

        firstImage =nil;
        [secondImage drawAtPoint:CGPointMake(roundf((newImageSize.width-secondImage.size.width)/2), roundf((newImageSize.height-secondImage.size.height)/2))];


        secondImage=nil;

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

我一次调用此函数5次,并根据此函数的返回图像设置UIImageView。

但是在执行时,内存总是会增加,并且在一段时间之后应用程序将崩溃。

那么,告诉我如何降低记忆压力?

1 个答案:

答案 0 :(得分:0)

您的问题可能来自其他问题。我只是在你的功能上运行乐器,所有接缝都能正常工作。

当我点击运行代码的按钮时出现尖峰。 enter image description here

这是代码:

+ (UIImage*)imageByCombiningImages:(UIImage*)firstImage withImage:(UIImage*)secondImage
{
    @autoreleasepool
    {
        UIImage *image = nil;

        CGSize newImageSize = CGSizeMake(MAX(firstImage.size.width, secondImage.size.width), MAX(firstImage.size.height, secondImage.size.height));
        if (UIGraphicsBeginImageContextWithOptions != NULL)
        {
            UIGraphicsBeginImageContextWithOptions(newImageSize, NO, [[UIScreen mainScreen] scale]);
        }
        else
        {
            UIGraphicsBeginImageContext(newImageSize);
        }

        [firstImage drawAtPoint:CGPointMake(roundf((newImageSize.width-firstImage.size.width)/2), roundf((newImageSize.height-firstImage.size.height)/2))];

        firstImage =nil;
        [secondImage drawAtPoint:CGPointMake(roundf((newImageSize.width-secondImage.size.width)/2), roundf((newImageSize.height-secondImage.size.height)/2))];


        secondImage=nil;

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

- (IBAction)callFunctionAction:(id)sender
{
    UIImage *firstImage = [UIImage imageNamed:@"image1"];
    UIImage *secondImage = [UIImage imageNamed:@"image2"];

    UIImage *thirdImage = [[self class] imageByCombiningImages:firstImage withImage:secondImage];
    self.imageView.image = thirdImage;
}

最后一行会发出警告,但示例仍然有效。