掩盖UIImage时出现问题

时间:2010-09-04 19:18:16

标签: iphone image-manipulation

我从以下网址获取了示例代码:how to mask an image以掩盖图片。

代码在iPhone模拟器上完美运行,但在iPhone 4模拟器上运行不正确(即加载高分辨率图像时...)

这是我的代码和掩码功能:

- (void)someMethod {

    UIImage* image = [UIImage imageNamed:@"image.png"];  // image@2x.png is loaded for high-res device

    UIImage* mask = [UIImage imageNamed:@"mask.png"];  // mask@2x.png is loaded for high-res device

    UIImage* maskedImage = [self maskImage:image withMask:mask];

    // ... Some code here displaying maskedImage

}

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

    UIImage* maskedImage = nil;

    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);
    maskedImage = [UIImage imageWithCGImage:masked];

    return maskedImage;
}

在iPhone 4模拟器上加载image@2x.png和mask@2x.png,然后裁剪产生的maskedImage。

知道我做错了什么吗?

2 个答案:

答案 0 :(得分:1)

使用此方法代替上述

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

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    //UIImage *maskImage = [UIImage imageNamed:@"mask.png"];
    CGImageRef maskImageRef = [maskImage CGImage];

    // create a bitmap graphics context the size of the image
    CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);


    if (mainViewContentContext==NULL)
        return NULL;

    CGFloat ratio = 0;

    ratio = maskImage.size.width/ image.size.width;

    if(ratio * image.size.height < maskImage.size.height) {
        ratio = maskImage.size.height/ image.size.height;
    } 

    CGRect rect1  = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
    CGRect rect2  = {{-((image.size.width*ratio)-maskImage.size.width)/2 , -((image.size.height*ratio)-maskImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}};


    CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
    CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);


    // Create CGImageRef of the main view bitmap content, and then
    // release that bitmap context
    CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
    CGContextRelease(mainViewContentContext);

    UIImage *theImage = [UIImage imageWithCGImage:newImage];

    CGImageRelease(newImage);

    // return the image
    return theImage;
}

答案 1 :(得分:0)

我的猜测是不要相信UIImage将高雷兹格式传递给CGImageRefs等。我想你需要手动完成。