我正在尝试制作一个简单的图像橡皮擦工具,用户可以像在下图中那样擦除和还原图像的绘画:
经过多次尝试和测试,我已经在 UI 界面上用以下代码实现了足够的“擦除”功能:
// Drawing code - on user touch
// `currentPath` is a `UIBezierPath` property of the containing class.
guard let image = pickedImage else { return }
UIGraphicsBeginImageContextWithOptions(imageView.frame.size, false, 0)
if let context = UIGraphicsGetCurrentContext() {
mainImageView.layer.render(in: context)
context.addPath(currentPath.cgPath)
context.setBlendMode(.clear)
context.setLineWidth(translatedBrushWidth)
context.setLineCap(.round)
context.setLineJoin(.round)
context.setStrokeColor(UIColor.clear.cgColor)
context.strokePath()
let capturedImage = UIGraphicsGetImageFromCurrentImageContext()
imageView.image = capturedImage
}
UIGraphicsEndImageContext()
当用户触摸图像后,我会对currentPath
应用比例变换,以完整的大小呈现带有剪切部分的图像,以保持UI性能。
现在我想弄清楚的是如何实现“还原”功能。基本上,用户应该在擦除的部分上绘制以显示原始图像。
我尝试查看了CGContextClipToMask
,但不确定如何实现。
我还尝试过其他方法来实现在渲染实际图像之前达到“擦除/还原”效果,例如在图像上覆盖CAShapeLayer
进行遮罩处理,但是这种方法也存在还原问题。
非常感谢任何帮助,以及在UI级别和渲染级别上使用路径擦除和还原的替代方法。 谢谢!