Akash Bakshi Akash Bakshi - 1 month ago 5x
iOS Question

Save/Retrieve User drawing Core Graphics &swift

Hey guys so I'm working on an app using the apple pencil, and there aren't many resources around on this so hopefully someone here can help.

What i'm my app does is it let's the user draw an image using the apple pencil, a UIImage view and core graphics to create the context and such. I now want to be able to save what the user has drawn ideally using NSData, however since it's being saved as a PNG how would I be able to load that saved file and get it on the UIImage screen again?


Here's my Core Graphics code :

let π = CGFloat(M_PI)

class NoteCanvasView: UIImageView {

private var defaultLineWidth:CGFloat = 1

private var drawColor: UIColor = UIColor.blackColor()

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else { return }

UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()

// Draw previous image into context

drawStroke(context, touch: touch)

// Update image
image = UIGraphicsGetImageFromCurrentImageContext()

private func drawStroke(context: CGContext?, touch: UITouch) {
let previousLocation = touch.previousLocationInView(self)
let location = touch.locationInView(self)

// Calculate line width for drawing stroke
let lineWidth = lineWidthForDrawing(context, touch: touch)

// Set color

// Configure line
CGContextSetLineWidth(context, lineWidth)
CGContextSetLineCap(context, .Round)

// Set up the points
CGContextMoveToPoint(context, previousLocation.x, previousLocation.y)
CGContextAddLineToPoint(context, location.x, location.y)
// Draw the stroke


private func lineWidthForDrawing(context: CGContext?, touch: UITouch) -> CGFloat {

var lineWidth = defaultLineWidth

return lineWidth
func saveNote(){
let data = UIImagePNGRepresentation(image!)
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(data, forKey: "test123")

func retrieveNote(){
if let data = NSUserDefaults.standardUserDefaults().dataForKey("test123"),let image = UIImage(data: data){



func setStrokeColor(color: UIColor){
drawColor = color
func setStrokeWidth(size: CGFloat){
defaultLineWidth = size

func clearCanvas(animated animated: Bool) {
if animated {
UIView.animateWithDuration(0.2, animations: {
self.alpha = 0
}, completion: { finished in
self.alpha = 1
self.image = nil
} else {
image = nil



you can got image back from data like,


take UIImage reference and get image like this and you can display that image on your imageview

hope this will help :)