Skip to content

Instantly share code, notes, and snippets.

@denisoliveira
Created March 25, 2020 15:07
Show Gist options
  • Save denisoliveira/c740ad6606e2877e1bf820fe114415b1 to your computer and use it in GitHub Desktop.
Save denisoliveira/c740ad6606e2877e1bf820fe114415b1 to your computer and use it in GitHub Desktop.
import UIKit
import CoreGraphics
public class DrawView: UIView {
@IBInspectable public var drawColor: UIColor = .black
@IBInspectable public var lineWidth: CGFloat = 3
private lazy var lastPoint: CGPoint = .zero
private lazy var bezierPath: UIBezierPath = {
let path = UIBezierPath()
path.lineCapStyle = .round
path.lineJoinStyle = .round
return path
}()
// MARK: - Lifecycle Methods
override public func draw(_ rect: CGRect) {
super.draw(rect)
drawColor.setStroke()
bezierPath.lineWidth = lineWidth
bezierPath.stroke()
}
// MARK: - Touch Handling Methods
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let point = touches.first?.location(in: self) else { return }
lastPoint = point
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
guard let newPoint = touches.first?.location(in: self) else { return }
bezierPath.move(to: lastPoint)
bezierPath.addLine(to: newPoint)
lastPoint = newPoint
setNeedsDisplay()
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
setNeedsDisplay()
}
public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
setNeedsDisplay()
}
// MARK: - Public Methods
public func clear() {
bezierPath.removeAllPoints()
setNeedsDisplay()
}
public func hasDraw() -> Bool {
return !bezierPath.isEmpty
}
public func renderToImage() -> UIImage? {
UIGraphicsBeginImageContext(frame.size)
defer {
UIGraphicsEndImageContext()
}
drawColor.setStroke()
bezierPath.lineWidth = lineWidth
bezierPath.stroke()
return UIGraphicsGetImageFromCurrentImageContext()
}
public func renderFitToImage() -> UIImage? {
UIGraphicsBeginImageContext(bezierPath.bounds.size)
defer {
UIGraphicsEndImageContext()
}
let origin = bezierPath.bounds.origin
bezierPath.apply(CGAffineTransform(
translationX: -origin.x,
y: -origin.y
))
drawColor.setStroke()
bezierPath.lineWidth = lineWidth
bezierPath.stroke()
return UIGraphicsGetImageFromCurrentImageContext()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment