我有一个不透明的图像和一个不透明的蒙版图像。使用MetalPetal
及其MTIBlendWithMaskFilter
,我可以创建一个输出图像,该图像可以正确遮罩输入图像,但是不透明,具有黑色背景。
我希望输出图像具有Alpha通道,例如代替黑色像素而具有透明像素。
func mt_blend(image: UIImage, with mask: UIImage) -> UIImage {
let ciMaskImage = CIImage(cgImage: mask.cgImage!)
let mtiMaskImage = MTIImage(ciImage: ciMaskImage, isOpaque: true)
let mtiMask = MTIMask(content: mtiMaskImage)
let ciImage = CIImage(cgImage: image.cgImage!)
let mtiImage = MTIImage(ciImage: ciImage, isOpaque: true)
let contextOptions = MTIContextOptions()
let context = try! MTIContext(device: MTLCreateSystemDefaultDevice()!, options: contextOptions)
let blendFilter = MTIBlendWithMaskFilter()
blendFilter.inputMask = mtiMask
blendFilter.inputBackgroundImage = mtiMaskImage
blendFilter.inputImage = mtiImage
let outputImage = try! context.makeCGImage(from: blendFilter.outputImage!)
return UIImage(cgImage: outputImage)
}
这似乎是我对预乘Alpha的误解或误用。
输入图片:
蒙版图像:
输出图像:
答案 0 :(得分:2)
您将混合滤镜的backgroundImage设置为遮罩不透明的图像。要获得透明背景,请将backgroundImage设置为透明颜色。
blendFilter.inputBackgroundImage = MTIImage.init(color: MTIColor.clear, sRGB: false, size: mtiImage.size)
MTIBlendWithMaskFilter
的输出图像尺寸将等于inputBackgroundImage
的尺寸。根据需要设置大小。