0
我有一個正方形的圖像,代表一個由白色圍成的厚圓圈,另一個正方形圖像代表一張臉。我想用圓圈掩蓋第二張圖像,以便最終圖像是第二張圖像的臉部帶有瑕疵的粗圓。目標c如何實現?如何用ios中的圖像遮罩圖像?
我有一個正方形的圖像,代表一個由白色圍成的厚圓圈,另一個正方形圖像代表一張臉。我想用圓圈掩蓋第二張圖像,以便最終圖像是第二張圖像的臉部帶有瑕疵的粗圓。目標c如何實現?如何用ios中的圖像遮罩圖像?
最後我使用該功能
+ (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();
這裏是圖像。保存並打開它以查看透明度。 (imgCircleMask是白色圖像在白色背景上在這裏) imgCircleMask
imgCircleHole
imgToBeMasked
imgResult
finalImage
希望幫助somenone!