Permalink
Browse files

Takes into account previous velocity and width, limits width step cha…

…nges
  • Loading branch information...
DarthMike committed Aug 9, 2015
1 parent 4658a56 commit 9cc66287a495a84e5bb2857350255d793461a0a2
Showing with 27 additions and 5 deletions.
  1. +7 −1 FreehandDrawing-iOS/FreehandDrawController.swift
  2. +20 −4 FreehandDrawing-iOS/WidthModulation.swift
@@ -72,7 +72,7 @@ class FreehandDrawController : NSObject {
}
private func continueAtPoint(point: CGPoint, velocity: CGPoint) {
let segmentWidth = modulatedWidth(self.width, velocity)
let segmentWidth = modulatedWidth(self.width, velocity, self.lastVelocity, self.lastWidth ?? self.width)
let segment = Segment(a: self.lastPoint, b: point, width: segmentWidth)
let lineCommand = LineDrawCommand(current: segment, previous: lastSegment, width: segmentWidth, color: self.color)
@@ -82,6 +82,8 @@ class FreehandDrawController : NSObject {
self.lineStrokeCommand?.addCommand(lineCommand)
self.lastPoint = point
self.lastSegment = segment
self.lastVelocity = velocity
self.lastWidth = segmentWidth
}
private func endAtPoint(point: CGPoint) {
@@ -91,6 +93,8 @@ class FreehandDrawController : NSObject {
self.lastPoint = CGPointZero
self.lastSegment = nil
self.lastVelocity = CGPointZero
self.lastWidth = nil
self.lineStrokeCommand = nil
}
@@ -105,4 +109,6 @@ class FreehandDrawController : NSObject {
private var commandQueue: Array<DrawCommand> = []
private var lastPoint: CGPoint = CGPointZero
private var lastSegment: Segment?
private var lastVelocity: CGPoint = CGPointZero
private var lastWidth: CGFloat?
}
@@ -24,16 +24,32 @@ THE SOFTWARE.
import UIKit
func modulatedWidth(width: CGFloat, velocity: CGPoint) -> CGFloat {
func modulatedWidth(width: CGFloat, velocity: CGPoint, previousVelocity: CGPoint, previousWidth: CGFloat) -> CGFloat {
let velocityAdjustement: CGFloat = 600.0
let speed = velocity.length() / velocityAdjustement
let modulated = width / speed
return modulated
let previousSpeed = previousVelocity.length() / velocityAdjustement
let modulated = width / (0.6 * speed + 0.4 * previousSpeed)
let limited = clamp(modulated, 0.75 * previousWidth, 1.25 * previousWidth)
let final = clamp(limited, 0.2*width, width)
return final
}
extension CGPoint {
func length() -> CGFloat {
return sqrt((self.x*self.x) + (self.y*self.y))
}
}
func clamp<T: Comparable>(value: T, min: T, max: T) -> T {
if (value < min) {
return min
}
if (value > max) {
return max
}
return value
}

0 comments on commit 9cc6628

Please sign in to comment.