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

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 apps Boyfriend & 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值