Implement a drawing app in Swift

I

Implement smooth drawing in iOS using swift.

A drawing app allows the user to draw on the screen with their finger. There are many companies  ask customers to sign on apple device when making purchases. 

Steps

1> create a custom class line for initializing values of start and end point of line

import UIKit

class Line{

  var start : CGPoint

  var end : CGPoint

  init(start _start : CGPoint , end _end : CGPoint) {

    start = _start

    end = _end

  }

}

2> We will create a custom drawview UIView class.  for drawing line from start and end point using draw function,   So that it can act like a canvas for our drawing app.  

import UIKit

class DrawView: UIView {

  var lines : [Line] = []

  var lastPoint : CGPoint!

  required init(coder aDecoder : NSCoder) {

    super.init(coder: aDecoder)!

  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    lastPoint = touches.first?.location(in: self)

  }  

  override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    let newPoint = touches.first?.location(in: self)

    lines.append(Line(start: lastPoint, end: newPoint!))

    lastPoint = newPoint

    self.setNeedsDisplay()

  }

  

  override func draw(_ rect: CGRect) {

    var context = UIGraphicsGetCurrentContext()

    context?.beginPath()

    for line in lines

    {

      let aPath = UIBezierPath()

      aPath.lineWidth = 5.0

      aPath.lineJoinStyle = .round

      aPath.move(to: CGPoint(x:line.start.x,y:line.start.y))

      aPath.addLine(to: CGPoint(x:line.end.x,y:line.end.y))

       aPath.stroke()

      aPath.lineCapStyle = .round

      //cgcontextSetLineCap()

    }

 }

}

3> write controller class in which we are using the draw view class for drawing line

import UIKit

class ViewController: UIViewController {

  @IBOutlet var drawView : AnyObject!

  override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

  }

  override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

  }

@IBAction func clearbutton()

{

  let theDrawView : DrawView = drawView as! DrawView

  theDrawView.lines = []

  theDrawView.setNeedsDisplay()

  }

}

Happy Drawing

About the author

Swarupa Doiphode
By Swarupa Doiphode

Category