Create a paw print in Core Drawing

Warren
2 min readAug 28, 2018

--

Here is a walkthrough on how to draw a paw print in Core Drawing. The end result is a UIImage you can place anywhere in your iOS project. Instead of talking through each line I thought it would be easier to understand as one code section with comments. You can use this in a playground and see the image right there.

// Core Drawing Contexts

import UIKit

// set size of drawing
var size = CGSize(width: 400, height: 400)

// position of drawing
let rect = CGRect(origin: .zero, size: size)
let backgroundColor = UIColor.red
let drawingColor = UIColor.white
let lineWidth:CGFloat = 5.0

// set up the context and allocate memory
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()

// create a line arount the edge with rounded corners
let edge = UIBezierPath(roundedRect: rect.insetBy(dx: lineWidth/2, dy: lineWidth/2), cornerRadius: 50)
context!.saveGState()

// clip the edge so you can still see your drawing in the center portion
edge.addClip()
// fill the background, and draw the edge
backgroundColor.setFill()
UIRectFill(rect)
context!.saveGState()
edge.lineWidth = lineWidth
drawingColor.setStroke()
edge.stroke()

// draw pads
let padWidth = 75; let padHeight = 95
let pad1 = UIBezierPath(ovalIn: CGRect(x: 75, y: 115, width: padWidth, height: padHeight))
pad1.lineWidth = lineWidth
pad1.stroke()
let pad2 = UIBezierPath(ovalIn: CGRect(x: 165, y: 70, width: padWidth, height: padHeight))
pad2.lineWidth = lineWidth
pad2.stroke()
let pad3 = UIBezierPath(ovalIn: CGRect(x: 255, y: 115, width: padWidth, height: padHeight))
pad3.lineWidth = lineWidth
pad3.stroke()
let pad4 = UIBezierPath(ovalIn: CGRect(x: 135, y: 190, width: padWidth + 60, height: padHeight + 50))
pad4.lineWidth = lineWidth
pad4.stroke()

// retrieve the drawing in to a UIImage
let image = UIGraphicsGetImageFromCurrentImageContext()
// end the context and de allocate memory
UIGraphicsEndImageContext()

// here is your image. click on the box on the far right to see the drawing right here in the playground
image

Originally published at Swift Sense.

--

--