Tuesday, December 9, 2008

Masking an image

Original post from iPhone Developer Tips
Masking an image enables a developer to create images with irregular shapes dynamically.

The following is a function that takes two images and uses one to mask the other.

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

}


NOTE: The mask image cannot have ANY transparency. Instead, transparent areas must be white or some value between black and white. The more towards black a pixel is the less transparent it becomes.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home