通过另一张图片对图像进行遮罩处理

3

我想做的是:

  • 给定一张图像,在这张图像中有一个“空白”的圆形。我想从用户库中选择一张现有的图像,然后对其进行蒙版处理,以便仅在“空白”图像上显示该图像的某个部分。

我尝试了几种蒙版代码,但它们似乎都是反过来工作的... 有什么技巧可以解决这个问题吗?

1个回答

5

很遗憾,你无法使用 CoreAnimation 来实现这个(否则会变得相当容易)。查看苹果公司的 CoreAnimation 文档

iOS 注意事项:出于性能考虑,iOS 不支持 mask 属性。

因此,最好的方法是使用 Quartz 2D(如 这里 所回答的):

CGContextRef mainViewContentContext;
CGColorSpaceRef colorSpace;

colorSpace = CGColorSpaceCreateDeviceRGB();

// create a bitmap graphics context the size of the image
mainViewContentContext = CGBitmapContextCreate (NULL, targetSize.width, targetSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);

// free the rgb colorspace
CGColorSpaceRelease(colorSpace);    

if (mainViewContentContext==NULL)
    return NULL;

CGImageRef maskImage = [[UIImage imageNamed:@"mask.png"] CGImage];
CGContextClipToMask(mainViewContentContext, CGRectMake(0, 0, targetSize.width, targetSize.height), maskImage);
CGContextDrawImage(mainViewContentContext, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), self.CGImage);


// Create CGImageRef of the main view bitmap content, and then
// release that bitmap context
CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext);
CGContextRelease(mainViewContentContext);

// convert the finished resized image to a UIImage 
UIImage *theImage = [UIImage imageWithCGImage:mainViewContentBitmapContext];
// image is retained by the property setting above, so we can 
// release the original
CGImageRelease(mainViewContentBitmapContext);

// return the image
return theImage;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接