我有一张图片:
我想申请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
但是这给了我相反的效果,波形被切除了:
我希望波形的外部区域是透明的,并且内部要着色。我打算将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 :(得分: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