UIView反转掩码MaskView

时间:2017-10-21 11:25:38

标签: swift uiview mask

我想在我的UIView上应用倒置的面具。我将掩码设置为带有透明图像的UIImageView。但输出

view.mask = imageView

不是理想的结果。如何如下图所示,我如何达到预期的效果?所需结果使用蒙版剪切作为透明度。当我检查View的掩码时,它不是CAShapeLayer所以我无法以这种方式反转它。

An illustration of what happens vs what I want.

1 个答案:

答案 0 :(得分:4)

好像你可以做一些事情。您可以使用您拥有的图像,但屏蔽白色视图并在其后面放置蓝色视图。或者,您可以通过反转透明度来调整您正在使用的图像资源。或者您可以使用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
}