ios - 使用 CGLayerRef 和 CGContextDrawLayerInRect mask 图像

标签 ios objective-c uiimage core-graphics cgcontextref

我想在离屏渲染中使用 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。

我通过以下步骤解决了该问题:

  1. 画出你的面具
  2. 将混合模式更改为 CGBlendMode.sourceIn
  3. 绘制您的“彩色”图像。

这是有效的,因为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/

相关文章:

ios - 从类中删除所有观察者

objective-c - 在表格 View 中显示图像单元格

objective-c - NIB 文件和版本控制 : Using branches

ios - 如何子类化 UILabel?

iphone - 在选取器 View 中未选择第一个值

iOS - 以编程方式创建 UIScrollView,直接分配与属性

ios - NSURLSessionConfiguration 和 NSMutableURLRequest 缓存策略的区别

ios - 如何使用 Swift 获取 UIImage 中像素的颜色?

ios - 将 UIImage 转换为 Keras 模型的 MLMultiArray

ios - 自定义 UISlider 图像无法正常工作