Episode #282

Paths

Series: Dive Into Core Graphics

17 minutes
Published on July 7, 2017

This video is only available to subscribers. Get access to this video and 582 others.

Learn the basics of UIBezierPath and CGPathRef for representing drawing operations as a primitive type. Paths are incredibly useful to drawing and can be used to represent arbitrary lines, curves, and shapes.

Drawing a Heart (Poorly)

let path = CGMutablePath()

// Heart
path.move(to: CGPoint(x: 100, y: 100))
path.addLine(to: CGPoint(x: 150, y: 150))
path.addLine(to: CGPoint(x: 200, y: 100))
path.addQuadCurve(to: CGPoint(x: 150, y: 80), control: CGPoint(x: 175, y: 50))
path.addQuadCurve(to: CGPoint(x: 100, y: 100), control: CGPoint(x: 125, y: 50))
context.addPath(path)
context.setLineWidth(10)
context.setLineCap(.round)
context.setLineJoin(.round)
context.setStrokeColor(UIColor.red.cgColor)
context.strokePath()

Fill Rules

 // Fill
path.addRect(CGRect(x: 50, y: 50, width: 100, height: 100))

 // Remove
path.addRect(CGRect(x: 75, y: 75, width: 50, height: 50))

// Fill
path.addRect(CGRect(x: 75, y: 100, width: 50, height: 10))

context.addPath(path)
context.setFillColor(UIColor.blue.cgColor)
context.fillPath(using: .evenOdd)

This episode uses Swift 3.0, Xcode 8.3.