我正在尝试获取应用于 UIImageView
的 mask 的 UIImage
。
我正在使用 UIBezierPath
添加 mask ,并希望将实际 mask 层作为 UIImage
,而不是整个图像。将其视为裁剪功能。
我正在使用以下方式裁剪图像:
func cropImage() {
shapeLayer.fillColor = UIColor.black.cgColor
viewSource.imageView.layer.mask = shapeLayer
viewSource.imageView.layer.masksToBounds = true
UIGraphicsBeginImageContextWithOptions(viewSource.imageView.bounds.size, false, 1)
viewSource.imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.completionObservable.onNext(newImage)
}
这最终为我提供了旧尺寸(初始 imageView 宽度和高度)之上的蒙版图像。但我只想拥有蒙版图像,不包括它们周围的白色背景。
界面如图:
最佳答案
我现在明白你的意思了。答案在这里,只需更新 imageContext 的大小即可。
UIGraphicsBeginImageContextWithOptions((shapeLayer.path?.boundingBoxOfPath)!.size, false, 1)
如果不是那么简单,可以试试CIImage管道来实现。
let context = CIContext()
let m1 = newImage?.cgImage
let m = CIImage.init(cgImage: m1!)
let bounds = imageView.layer.bounds
let cgImage = context.createCGImage(m, from: CGRect.init(x: 0, y: bounds.size.height, width: bounds.size.width, height: bounds.size.height))
let newUIImage = UIImage.init(cgImage: cgImage!)
您可能需要调整变换。
关于swift - 在 UIImageView 之上的 Swift 上将蒙版层作为 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54316574/