Permalink
Browse files

Adds naive DrawView implementation

  • Loading branch information...
DarthMike committed May 20, 2015
1 parent b6e7e36 commit 5ae6497ee083ec863cb2131730bd924de367600f
Showing with 57 additions and 0 deletions.
  1. +57 −0 FreehandDrawing-iOS/DrawView.swift
@@ -27,7 +27,64 @@ import UIKit
class DrawView : UIView {
override func awakeFromNib() {
super.awakeFromNib()
+ self.setupGestureRecognizers()
+ }
+
+ // MARK: Drawing a path
+
+ override func drawRect(rect: CGRect) {
+ // 4. Redraw whole rect, ignoring parameter. Please note we always invalidate whole view.
+ let context = UIGraphicsGetCurrentContext()
+ self.drawColor.setStroke()
+ self.path.lineWidth = self.drawWidth
+ self.path.lineCapStyle = kCGLineCapRound
+ self.path.stroke()
+ }
+
+ // MARK: Gestures
+
+ private func setupGestureRecognizers() {
+ // 1. Set up a pan gesture recognizer to track where user moves finger
+ let panRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
+ self.addGestureRecognizer(panRecognizer)
+ }
+
+ @objc private func handlePan(sender: UIPanGestureRecognizer) {
+ let point = sender.locationInView(self)
+ switch sender.state {
+ case .Began:
+ self.startAtPoint(point)
+ case .Changed:
+ self.continueAtPoint(point)
+ case .Ended:
+ self.endAtPoint(point)
+ case .Failed:
+ self.endAtPoint(point)
+ default:
+ assert(false, "State not handled")
+ }
+ }
+
+ // MARK: Tracing a line
+
+ private func startAtPoint(point: CGPoint) {
+ self.path.moveToPoint(point)
+ }
+
+ private func continueAtPoint(point: CGPoint) {
+ // 2. Accumulate points as they are reported by the gesture recognizer, in a bezier path object
+ self.path.addLineToPoint(point)
+
+ // 3. Trigger a redraw every time a point is added (finger moves)
+ self.setNeedsDisplay()
+ }
+
+ private func endAtPoint(point: CGPoint) {
+ // Nothing to do when ending/cancelling for now
}
var drawColor: UIColor = UIColor.blackColor()
+ var drawWidth: CGFloat = 10.0
+
+ private var path: UIBezierPath = UIBezierPath()
}

0 comments on commit 5ae6497

Please sign in to comment.