I want to draw some shapes like someone's signature or some other freehand shapes. I am new to UIBezierPath. I have tried following code but it didn't works as I want.
How could be it possible ? TIA
let path = UIBezierPath()
path.move(to: from)
path.addLine(to: to)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = lineColor.cgColor
shapeLayer.lineWidth = 1.0
view.layer.addSublayer(shapeLayer)
Here is a basic drawing code, you should add UIImageView
to paint on it, basically you need to paint a line between the previous touched point and the current point, using line cap .round
import UIKit
class BasicDrawingViewController: UIViewController {
var lastPoint = CGPoint.zero
var paintColor : UIColor = UIColor.black
var lineWidth : CGFloat = 20.0
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//Draw logic
extension BasicDrawingViewController{
func drawBetweenPoints(point1:CGPoint,point2:CGPoint){
UIGraphicsBeginImageContext(self.imageView.bounds.size)
let context = UIGraphicsGetCurrentContext()
self.imageView.image?.draw(in: self.imageView.bounds)
context?.move(to: point1)
context?.addLine(to: point2)
context?.setLineCap(.round)
context?.setStrokeColor(self.paintColor.cgColor)
context?.setLineWidth(lineWidth)
context?.strokePath()
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
debugPrint("Began")
if let touch = touches.first{
let point = touch.location(in: self.imageView)
self.drawBetweenPoints(point1: point, point2: point)
self.lastPoint = point
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
debugPrint("Move")
if let touch = touches.first{
let newPoint = touch.location(in: self.imageView)
self.drawBetweenPoints(point1: self.lastPoint, point2: newPoint)
self.lastPoint = newPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
debugPrint("Ended")
if let touch = touches.first{
let point = touch.location(in: self.imageView)
debugPrint(point)
}
}
}
Storyboard Setup
Result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With