2017-10-21 76 views
1

我想对我的UIView应用翻转掩码。我将掩码设置为具有透明图像的UIImageView。然而,输出与UIView翻转掩码MaskView

view.mask = imageView 

不是所需的结果。我如何达到预期的效果,如下图所示?期望的结果使用掩模切口作为透明度。当我检查视图的蒙版时,它不是CAShapeLayer,所以我不能以这种方式反转。

An illustration of what happens vs what I want.

+0

[在drawRect中的iOS转化面具]的可能的复制(https://stackoverflow.com/questions/14411765/ios-invert-mask-in-drawrect) – the4kman

回答

2

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

惊人!我唯一的问题是imageView比UIView小,所以mask只显示带有切口的倒影。我该如何解决这个问题? –

+1

我认为最简单的方法是将'imageView'的'frame'设置为与您屏蔽的视图相同的大小,并将'imageView'的'contentMode'设置为'.scaleAspectFill',但这很难准确地知道该怎么做。也许你可以用你想要发生的事情来更新你的问题。 – beyowulf