Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView invert mask MaskView

Tags:

swift

uiview

mask

I want to apply an inverted mask to my UIView. I set the mask to a UIImageView with a transparent image. However the output with

view.mask = imageView

is not the desired result. How can I achieve the desired result as I illustrated below? The desired result uses the mask cutout as transparency. When I check the mask of the View, it isn't a CAShapeLayer so I can't invert it that way.

An illustration of what happens vs what I want.

like image 300
evenwerk Avatar asked Oct 21 '17 11:10

evenwerk


1 Answers

Seems like you could do a few things. You could use the image you have but mask a white view and place a blue view behind it. Or you could adjust the image asset you’re using to by reversing the transparency. Or you could use CoreImage to do that in code. For example:

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
}
like image 146
beyowulf Avatar answered Sep 28 '22 06:09

beyowulf