Problem when masking UIImage
I took a sample code from the following URL: how to mask an image in order to mask an image.
The code is working perfectly on the iPhone simulator but works incorrectly on iPhone 4 simulator (that's when high-res images are loaded...)
Here is my code and the mask function开发者_开发问答:
- (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;
}
On the iPhone 4 simulator the image@2x.png and mask@2x.png are loaded and then the resulted maskedImage is cropped.
Any idea what am I doing wrong?
Use this method instead of above
- (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;
}
My guess would be to not trust UIImage to deliver the highrez format to CGImageRefs etc. I think you will need to do it manually.
精彩评论