如何用ios中的图像掩盖图像?

时间:2014-07-09 12:27:08

标签: ios image mask

我有一个正方形图像,表示一个由白色表示的粗圆圈,另一个正方形图像表示一张脸。我想用圆圈掩盖第二个图像,这样最终的图像就是第二个图像的面部的粗圆。如何在目标c中实现这一目标?

1 个答案:

答案 0 :(得分:1)

最后我使用了这个功能

+ (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage
{
    CGImageRef imgRef = [image CGImage];
    CGImageRef maskRef = [maskImage CGImage];
    CGImageRef actualMask = CGImageMaskCreate(
                                          CGImageGetWidth(maskRef),
                                          CGImageGetHeight(maskRef),
                                          CGImageGetBitsPerComponent(maskRef),
                                          CGImageGetBitsPerPixel(maskRef),
                                          CGImageGetBytesPerRow(maskRef),
                                          CGImageGetDataProvider(maskRef), NULL, false);
    CGImageRef masked = CGImageCreateWithMask(imgRef, actualMask);
    return [UIImage imageWithCGImage:masked];
}

和此代码

// Getting an image imgResult that is center of imgToBeMasked with the surrounding transparent
NSString *filePath_imgCircleMask = [[NSBundle mainBundle] pathForResource:@"imgCircleMask" ofType:@"png"];
NSString *filePath_imgToBeMasked = [[NSBundle mainBundle] pathForResource:@"imgToBeMasked" ofType:@"png"];
NSString *filePath_imgCircleHole = [[NSBundle mainBundle] pathForResource:@"imgCircleHole" ofType:@"png"];
UIImage *imgCircleMask = [UIImage imageWithContentsOfFile:filePath_imgCircleMask];
UIImage *imgToBeMasked = [UIImage imageWithContentsOfFile:filePath_imgToBeMasked];
UIImage *imgCircleHole = [UIImage imageWithContentsOfFile:filePath_imgCircleHole];
UIImage *imgResult =[funzioni maskImage:imgToBeMasked withMask:imgCircleMask];

// Merge imgResult with imgCircleHole so to obtain the img to be masked inside the circle
CGSize size = CGSizeMake(imgResult.size.width, imgResult.size.height);
UIGraphicsBeginImageContext(size);
[imgCircleHole drawInRect:CGRectMake(0,0,size.width, size.height)];
[imgResult drawInRect:CGRectMake(0,0,size.width, size.height)];
finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

以下是图片。保存它们并打开它以查看trasparency。 (imgCircleMask是白色背景上的白色图像) imgCircleMask

enter image description here

imgCircleHole

enter image description here

imgToBeMasked

enter image description here

imgResult

enter image description here

finalImage

enter image description here

希望帮助一些人!