UIView反转蒙版MaskView

eve*_*erk 5 mask uiview swift

我想对我的UIView应用倒置蒙版。我将蒙版设置为带有透明图像的UIImageView。但是输出

view.mask = imageView
Run Code Online (Sandbox Code Playgroud)

不是理想的结果。如下图所示,如何获得所需的结果?期望的结果使用蒙版切口作为透明度。当我检查视图的蒙版时,它不是CAShapeLayer,所以我不能那样翻转它。

发生的情况与我想要的情况的说明。

bey*_*ulf 6

似乎您可以做一些事情。您可以使用已有的图像,但可以遮盖白色视图,并在其后放置蓝色视图。或者,您可以通过反转透明度来调整要使用的图像资产。或者,您可以使用CoreImage代码来做到这一点。例如:

func invertMask(_ image: UIImage) -> UIImage?
{
    guard let inputMaskImage = CIImage(image: image),
        let backgroundImageFilter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: [kCIInputColorKey: CIColor.black]), 
        let inputColorFilter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: [kCIInputColorKey: CIColor.clear]), 
        let inputImage = inputColorFilter.outputImage, 
        let backgroundImage = backgroundImageFilter.outputImage,
        let filter = CIFilter(name: "CIBlendWithAlphaMask", withInputParameters: [kCIInputImageKey: inputImage, kCIInputBackgroundImageKey: backgroundImage, kCIInputMaskImageKey: inputMaskImage]),
        let filterOutput = filter.outputImage,
        let outputImage = CIContext().createCGImage(filterOutput, from: inputMaskImage.extent) else { return nil }
    let finalOutputImage = UIImage(cgImage: outputImage)
    return finalOutputImage
}
Run Code Online (Sandbox Code Playgroud)