Tuesday 22 May 2012

How to Mask an Image

How to Mask an Image

Masking an image enables a developer to create images with irregular shapes dynamically. Masking is often used to create a user interface that is more compelling and less boring.
Take for example the following example …
maskingstoryboard.png
Creating the mask above is really simple using CoreGraphics on the iPhone. The following is a function that takes two images and uses one to mask the other.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (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];
 
}

Yep … its just that simple!
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.

http://mobiledevelopertips.com/cocoa/how-to-mask-an-image.html

No comments:

Post a Comment