- 创建涂鸦效果层(用户操作层,把用户的操作轨迹显示出来)
class GraffitiView: UIView {
class GraffitiLine: UIBezierPath {
var lineColor: UIColor = .red
override init() {
super.init()
lineCapStyle = .round
lineJoinStyle = .round
lineWidth = 5
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private var lineArray = [GraffitiLine]()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
self.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(addLineAction(pan:))))
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
for line in lineArray {
line.lineColor.setStroke()
line.stroke()
}
}
func clear() {
lineArray.removeAll()
setNeedsDisplay()
}
// MARK: - actions
@objc func addLineAction(pan: UIPanGestureRecognizer) {
switch pan.state {
case .began:
let path = GraffitiLine()
path.move(to: pan.location(in: self))
lineArray.append(path)
case .changed:
lineArray.last?.addLine(to: pan.location(in: self))
setNeedsDisplay()
default:
print("")
}
}
}
- 使用GraffitiView 时 大小要与图片展示的大小一致,保证涂鸦范围与图片区域一致
推荐使用方法,直接放在图片上
graffitiMaskView.frame = imgView.bounds
imgView.isUserInteractionEnabled = true
imgView.addSubview(graffitiMaskView)
- 最后涂鸦完成后,进行图片合成
// 提取涂鸦层的图片
var graffitiImage: UIImage? = nil
UIGraphicsBeginImageContextWithOptions(graffitiMaskView.bounds.size, false, UIScreen.main.scale)
if let context = UIGraphicsGetCurrentContext() {
graffitiMaskView.layer.render(in: context)
graffitiImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
// 合成原始图片与涂鸦图片
UIGraphicsBeginImageContextWithOptions(clipSize, false, 1)
image?.draw(at: .zero)
graffitiImage?.draw(in: CGRect(origin: .zero, size: clipSize))
clippedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
网友评论