通过 Core Image 框架复制结果`func masking(_ mask: CGImage) -> CGImage?`

Replicate result `func masking(_ mask: CGImage) -> CGImage?` by Core Image framework

是否可以选择使用 CoreImage 和 CIFilter 之一从 Core Graphics 复制 func masking(_ mask: CGImage) -> CGImage??我试过 CIBlendWithMaskCIBlendWithAlphaMask 都没有成功。最重要的是我需要保留 alpha 通道,所以我希望以这种方式屏蔽图像,如果屏蔽是黑色 -> 显示图像,如果屏蔽是白色 -> 透明。 我的屏蔽码:

extension UIImage {
    
    func masked(by mask: UIImage) -> UIImage {
        guard let maskRef = mask.cgImage,
            let selfRef = cgImage,
            let dataProvider = maskRef.dataProvider,
            let mask = CGImage(
                maskWidth: maskRef.width,
                height: maskRef.height,
                bitsPerComponent: maskRef.bitsPerComponent,
                bitsPerPixel: maskRef.bitsPerPixel,
                bytesPerRow: maskRef.bytesPerRow,
                provider: dataProvider,
                decode: nil,
                shouldInterpolate: false),
            let masked = selfRef.masking(mask) else {
                    fatalError("couldnt create mask!")
        }
        let maskedImage = UIImage(cgImage: masked)
        return maskedImage
    }
}

您需要创建自己的自定义 CIFilter。教程:

Apple Docs

Apple Docs 2

Raywenderlich.com Tutorial

这不是微不足道的,但是当你学会如何去做时它会得到回报:)

我找到了解决方案。关键是使用具有灰度格式的图像,rgb 和其他将不起作用。如果图像和 maks 具有相同的大小,则可以删除调整大小的步骤。可以作为扩展,也可以作为 CIImage 的子类来完成。享受:)

当然可以修改为UIImageCIImageCIFilter的扩展,喜欢就好

extension CGImage {
    
    func masked(by cgMask: CGImage) -> CIImage {
        let selfCI = CIImage(cgImage: self)
        let maskCI = CIImage(cgImage: cgMask)
        
        let maskFilter = CIFilter(name: "CIMaskToAlpha")
        maskFilter?.setValue(maskCI, forKey: "inputImage")
        let scaleFilter = CIFilter(name: "CILanczosScaleTransform")
        scaleFilter?.setValue(maskFilter?.outputImage, forKey: "inputImage")
        scaleFilter?.setValue(selfCI.extent.height / maskCI.extent.height, forKey: "inputScale")
        let filter: CIFilter! = CIFilter(name: "CIBlendWithAlphaMask")
        filter.setValue(selfCI, forKey: "inputBackgroundImage")
        let maskOutput = scaleFilter?.outputImage
        filter.setValue(maskOutput, forKey: "inputMaskImage")
        let outputImage = filter.outputImage!
        return outputImage
    }
}