how-to-mask-images-with-core-graphics-in-ios ios Mask

来源:互联网 发布:hash算法 编辑:程序博客网 时间:2024/06/10 19:35

Masking an image enables us to create images with irregular shapes dynamically. Masking is often used to create a user interface that is more compelling, thus more interesting.  The appsBoyfriend & Girlfriend use masking to create their shapes and buttons. In this tutorial I want to explain what image masking is, and how to use it in iOS.

What is image masking? Here is the definition from the Apple documentation:

An image mask is a bitmap that specifies an area to paint, but not the color. In effect, an image mask acts as a stencil to specify where to place color on the page. Quartz uses the current fill color to paint an image mask.


When you want to get started with masking, you need two images. The first one is the original image, or the source image, and the other one is the image that will define the mask. A mask acts as an inverse alpha value, thus the black area will be transparent and the white area will be covered, everything in between will act as an alpha value of (255 -S) where S is the value of the color.

      


When you use those two images with the following function you’ll get the masked image as the returning result image.

- (UIImage*) maskImage:(UIImage *) image withMask:(UIImage *) mask{    CGImageRef imageReference = image.CGImage;    CGImageRef maskReference = mask.CGImage;        CGImageRef imageMask = CGImageMaskCreate(CGImageGetWidth(maskReference),                                             CGImageGetHeight(maskReference),                                             CGImageGetBitsPerComponent(maskReference),                                             CGImageGetBitsPerPixel(maskReference),                                             CGImageGetBytesPerRow(maskReference),                                             CGImageGetDataProvider(maskReference),                                             NULL, // Decode is null                                             YES // Should interpolate                                             );        CGImageRef maskedReference = CGImageCreateWithMask(imageReference, imageMask);    CGImageRelease(imageMask);    UIImage *maskedImage = [UIImage imageWithCGImage:maskedReference];    CGImageRelease(maskedReference);        return maskedImage;}From:  http://jeroendeleeuw.com/post/33638733049/how-to-mask-images-with-core-graphics-in-ios
原创粉丝点击