2017-10-21 106 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