我想在离屏渲染中使用 CGLayerRef 用另一个图像掩盖一个图像,因为它适合高质量渲染,正如文档中提到的
Core Graphics Layer Drawing : CGLayer objects allow your application to use layers for drawing. Layers are suited for the following: High-quality offscreen rendering of drawing that you plan to reuse.
但是我在 Objective-C 中找不到任何我可以理解它是如何工作的例子。在我的上下文中,我想用形状图像(纯色形状)掩盖图像,我曾经这样做过
//The context I use to mask my image with the mask image.
CGColorSpaceRef colorSpace= CGColorSpaceCreateDeviceRGB();
CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, _bigImageRect.size.width, _bigImageRect.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
//Mask image
CGContextClipToMask(mainViewContentContext,
CGRectMake(0,
-_bigImageRect.origin.y,
_bigImageRect.size.width,
_bigImageRect.size.height),
_maskImage.CGImage);
//Drawing the image on the mask image.
CGContextDrawImage(mainViewContentContext,
CGRectMake(0,
0,
_bigImageRect.size.width,
_bigImageRect.size.height),
_ImageToBeMasked.CGImage);
CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext);
CGContextRelease(mainViewContentContext);
UIImage*maskedImage = [UIImage imageWithCGImage:mainViewContentBitmapContext];
CGImageRelease(mainViewContentBitmapContext)
return maskedImage;
但是我如何使用 CGLayers 进行 mask ,如下所示?我感谢任何帮助。
CGLayerRef layer = CGLayerCreateWithContext(mainViewContentContext, _bigImageRect.size, NULL);
CGContextDrawLayerInRect(mainViewContentContext, _bigImageRect, layer);
CGLayerRelease(layer);
//And then.. how can I do the masking using this CGLayerRef???
最佳答案
我通常编写 Swift 代码,但有一次我还必须处理屏蔽和 CGLayer。
我通过以下步骤解决了该问题:
- 画出你的面具
- 将混合模式更改为
CGBlendMode.sourceIn
- 绘制您的“彩色”图像。
这是有效的,因为CGBlendMode.sourceIn
告诉上下文将源图像的alpha值与现有像素的颜色相乘。因此, mask 的不可见部分 (alpha = 0.0
) 将保持不可见。
CGBlendMode 的 Apple 文档:https://developer.apple.com/documentation/coregraphics/cgblendmode
关于ios - 使用 CGLayerRef 和 CGContextDrawLayerInRect mask 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48734422/