Skip to content

Instantly share code, notes, and snippets.

@codePrincess
Last active August 10, 2018 18:26
Show Gist options
  • Save codePrincess/9b3ee7788243001e23e674bb31ad5ad1 to your computer and use it in GitHub Desktop.
Save codePrincess/9b3ee7788243001e23e674bb31ad5ad1 to your computer and use it in GitHub Desktop.
Basic doodling with Apple Pencil
import Foundation
import UIKit
public class DoodleCanvas : UIImageView {
let pi = CGFloat(Double.pi)
let forceSensitivity: CGFloat = 4.0
var pencilTexture = UIColor(patternImage: UIImage(named: "PencilTexture")!)
let defaultLineWidth : CGFloat = 6
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
image?.draw(in: bounds)
drawStroke(context: context, touch: touch)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
func drawStroke(context: CGContext?, touch: UITouch) {
let previousLocation = touch.previousLocation(in: self)
let location = touch.location(in: self)
var lineWidth : CGFloat = 1.0
if touch.type == .stylus {
lineWidth = lineWidthForDrawing(context: context, touch: touch)
UIColor.darkGray.setStroke()
}
context!.setLineWidth(lineWidth)
context!.setLineCap(.round)
context?.move(to: previousLocation)
context?.addLine(to: location)
context!.strokePath()
}
func lineWidthForDrawing(context: CGContext?, touch: UITouch) -> CGFloat {
var lineWidth = defaultLineWidth
if touch.force > 0 {
lineWidth = touch.force * forceSensitivity
}
return lineWidth
}
func clearCanvas(_ animated: Bool) {
if animated {
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 0
}, completion: { finished in
self.alpha = 1
self.image = nil
})
} else {
image = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment