Jor*_*n H 7 compositing core-image cifilter swift ios11
我正在使用CISourceOverCompositing叠加图像顶部的文本,当文本图像不完全不透明时,我会得到意想不到的结果.深色不够暗,输出图像中的浅色太亮.
我在一个简单的Xcode项目中重新创建了这个问题.它创建一个图像,其中橙色,白色,黑色文本用0.3 alpha绘制,看起来是正确的.我甚至将该图像投入草图,将其放在背景图像的顶部,看起来很棒.屏幕底部的图像显示了Sketch中的外观.问题是,在使用背景上覆盖文本后CISourceOverCompositing,白色文本太不透明,好像alpha为0.5,而黑色文本几乎不可见,就好像alpha为0.1.顶部图像显示以编程方式创建的图像.您可以拖动滑块来调整alpha(默认值为0.3),这将重新创建结果图像.
代码当然包含在项目中,但也包含在此处.这将创建0.3 alpha的文本叠加层,其显示为预期.
let colorSpace = CGColorSpaceCreateDeviceRGB()
let alphaInfo = CGImageAlphaInfo.premultipliedLast.rawValue
let bitmapContext = CGContext(data: nil, width: Int(imageRect.width), height: Int(imageRect.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: alphaInfo)!
bitmapContext.setAlpha(0.3)
bitmapContext.setTextDrawingMode(CGTextDrawingMode.fill)
bitmapContext.textPosition = CGPoint(x: 20, y: 20)
let displayLineTextWhite = CTLineCreateWithAttributedString(NSAttributedString(string: "hello world", attributes: [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 50)]))
CTLineDraw(displayLineTextWhite, bitmapContext)
let textCGImage = bitmapContext.makeImage()!
let textImage = CIImage(cgImage: textCGImage)
Run Code Online (Sandbox Code Playgroud)
接下来,文本图像覆盖在背景图像的顶部,这不会按预期显示.
let combinedFilter = CIFilter(name: "CISourceOverCompositing")!
combinedFilter.setValue(textImage, forKey: "inputImage")
combinedFilter.setValue(backgroundImage, forKey: "inputBackgroundImage")
let outputImage = combinedFilter.outputImage!
Run Code Online (Sandbox Code Playgroud)
经过多次反复尝试不同的事情,(感谢@andy 和@Juraj Antas 将我推向正确的方向)我终于有了答案。因此,绘制到 Core Graphics 上下文中会产生正确的外观,但使用这种方法绘制图像的成本更高。看起来问题出在CISourceOverCompositing,但问题实际上在于,默认情况下,Core Image 过滤器在线性空间中工作,而 Core Graphics 在感知空间中工作,这解释了不同的结果。但是,您可以使用不执行颜色管理的 Core Image 上下文从 Core Image 过滤器创建 Core Graphics 图像,从而匹配 Core Graphics 方法的输出。所以原始代码就好了,只需要稍微不同地输出图像。
let ciContext = CIContext(options: [kCIContextWorkingColorSpace: NSNull()])
let outputImage = ciContext.createCGImage(outputCIImage, from: outputCIImage.extent)
//this image appears as expected
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1289 次 |
| 最近记录: |