屏蔽图像时崩溃

时间:2009-06-04 08:40:54

标签: iphone sdk

我试图用“掩码图像”掩盖图像。它第一次工作正常。但是当我在具有相同掩码图像的应用程序中再试一次时,应用程序崩溃了。尝试使用其他蒙版图像时效果很好。为什么会这样?

控制台显示<Error>: CGImageMaskCreate: invalid mask bits/component: 4294967295.

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    CGImageRef maskRef = maskImage.CGImage;

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
    CGImageGetHeight(maskRef),
    CGImageGetBitsPerComponent(maskRef),
    CGImageGetBitsPerPixel(maskRef),
    CGImageGetBytesPerRow(maskRef),
    CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
    UIImage *img2=[UIImage imageWithCGImage:masked];

    CGImageRelease(maskRef);
    CGImageRelease(mask);
    CGImageRelease(masked);

    return img2;
}

fun1()
{
view.image=[self maskImage:image1 withMask:[UIImage imageNamed:@"image2.png"]];
}

fun2()
{
view.image=[self maskImage:image1 withMask:[UIImage imageNamed:@"image2.png"]]; view.image=[self maskImage:image1 withMask:[UIImage imageNamed:@"image3.png"]];
}

fun3()
{
view.image=[self maskImage:image1 withMask:[UIImage imageNamed:@"image2.png"]];
view.image=[self maskImage:image1 withMask:[UIImage imageNamed:@"image2.png"]];
}

调用fun1fun2时,apllication工作正常。调用fun3时,应用程序崩溃。

2 个答案:

答案 0 :(得分:1)

你为什么要发布maskRef? 你不应该因为哟没有保留它。

答案 1 :(得分:1)

以下是您要做的事情,没有内存泄漏或崩溃:

    - (UIImage*) maskImage:(UIImage *)image
              withMask:(UIImage *)maskImage
{
        CGImageRef imageRef = image.CGImage;
        CGImageRef maskRef = maskImage.CGImage;  
        CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                      CGImageGetHeight(maskRef),
                                      CGImageGetBitsPerComponent(maskRef),
                                      CGImageGetBitsPerPixel(maskRef),
                                      CGImageGetBytesPerRow(maskRef),
                                      CGImageGetDataProvider(maskRef),
                                      NULL, // decode should be NULL
                                      FALSE // shouldInterpolate
                                      );

        CGImageRef masked = CGImageCreateWithMask(imageRef, mask);
        CGImageRelease(mask);
        UIImage *maskedImage = [UIImage imageWithCGImage:masked];
        CGImageRelease(masked);
        return maskedImage;
}