- 創(chuàng)建涂鴉效果層(用戶操作層帖池,把用戶的操作軌跡顯示出來(lái))
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 時(shí) 大小要與圖片展示的大小一致吭净,保證涂鴉范圍與圖片區(qū)域一致
推薦使用方法,直接放在圖片上
graffitiMaskView.frame = imgView.bounds
imgView.isUserInteractionEnabled = true
imgView.addSubview(graffitiMaskView)
- 最后涂鴉完成后寂殉,進(jìn)行圖片合成
// 提取涂鴉層的圖片
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()