2017-07-31 89 views
0

我有一個形象:用的UIImage面膜的UIView通過保持透明區域和取出彩色區域

enter image description here

,我想申請到UIView使彩色波形(透明區域)。我曾嘗試以下:

let image = UIImage(named: "waveform")! 

let view = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) 

let mask = CALayer() 
mask.frame = view.bounds 
mask.contents = image.cgImage! 

view.layer.mask = mask 
view.layer.masksToBounds = true 
view.backgroundColor = UIColor.green 

但是這給了我相反的效果,在波形切出:

enter image description here

我想波形的外側區域是透明的,並且內部被着色。我打算把UIView放在另一個視圖之上,所以我認爲它應該是一個面具。

我試着用CIImage在類似的問題提出反轉透明和彩色區域:

let cgImage = image.cgImage! 
let ciImage = CIImage(cgImage: cgImage) 
let filter = CIFilter(name: "CIColorInvert")! 
filter.setValue(ciImage, forKey: kCIInputImageKey) 

mask.contents = filter.outputImage!.cgImage 

...但是這導致了空白view(透明背景)。

任何幫助將不勝感激。

+0

我覺得你找這個[逆轉的CALayer面具(https://stackoverflow.com/a/42238699/6689101) – zombie

回答

1

這裏有一種方法......

func getImageWithInvertedPixelsOfImage(image: UIImage) -> UIImage { 
    let rect = CGRect(origin: CGPoint(), size: image.size) 

    UIGraphicsBeginImageContextWithOptions(image.size, false, 2.0) 
    UIGraphicsGetCurrentContext()!.setBlendMode(.copy) 
    image.draw(in: rect) 
    UIGraphicsGetCurrentContext()!.setBlendMode(.sourceOut) 
    UIGraphicsGetCurrentContext()!.setFillColor(UIColor.green.cgColor) 
    UIGraphicsGetCurrentContext()!.fill(rect) 

    let result = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 
    return result! 
} 

// I named your original image "WaveMask" 
let iWave = UIImage(named: "WaveMask") 
let invWave = getImageWithInvertedPixelsOfImage(image: iWave!) 

// invWave is now Green where it was alpha, and alpha where it was gray 
// and can now be used as a mask 
+0

謝謝!我花了好幾個小時試圖解決這個問題,這完美地工作。時間閱讀這些功能:) – Daven

相關問題