如何使用MetalPetal遮罩图像并透明输出

问题描述

我有一个不透明的图像和一个不透明的蒙版图像。使用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的误解或误用。

输入图片

enter image description here

蒙版图像:

enter image description here

输出图像:

enter image description here

解决方法

您将混合滤镜的backgroundImage设置为遮罩不透明的图像。要获得透明背景,请将backgroundImage设置为透明颜色。

blendFilter.inputBackgroundImage = MTIImage.init(color: MTIColor.clear,sRGB: false,size: mtiImage.size)

MTIBlendWithMaskFilter的输出图像尺寸将等于inputBackgroundImage的尺寸。根据需要设置大小。