UIKit Secrets
UIBeizerPath with an example using UIKit
Mastering the Spell: Unleashing the Magic of UIBezierPath in UIKit
This article has been updated and moved to my website here
Task
The composition of equilateral triangles alternating with squares. Aligning the Squares and equilateral triangles is straightforward, sum and multiplication should suffice.
Core Concept
For creating a shape or adding a line, we should go for UIBezierPath.
UIBezierPath
A path that consists of straight and curved line segments that you can render in your custom views.
class UIBezierPath : NSObject
A UIBezierPath
object combines the geometry of a path with attributes that describe the path during rendering.
Constructing a Path
move(to:) — Moves the path’s current point to the specified location.
func move(to point: CGPoint)
addLine(to:) — Appends a straight line to the path. Before calling this, we must set the path’s current point using move(to:) or through a previous line creation. If the path is empty, this method does nothing.
func addLine(to point: CGPoint)
Implementation
To create a square path
func getSquare(forEquilateralTriangle size: CGSize, origin: CGPoint) -> UIBezierPath {
guard size.width == size.height else {
fatalError(Constants.errorMessage)
}
let path = UIBezierPath()
let xAxis = origin.x
let yAxis = origin.y
let width = size.width
let height = size.height
path.move(to: CGPoint(x: xAxis + (width * 0.25), y: yAxis + size.height))
path.addLine(to: CGPoint(x: xAxis + (width * 0.25), y: yAxis + (height * 0.5)))
path.addLine(to: CGPoint(x: xAxis + (width * 0.75), y: yAxis + height * 0.5))
path.addLine(to: CGPoint(x: xAxis + (width * 0.75), y: yAxis + height))
path.addLine(to: CGPoint(x: xAxis + (width * 0.25), y: yAxis + height))
return path
}
To create an Equilateral Triangle path
func getEquilateralTrianglePath(forSize size: CGSize, origin: CGPoint) -> UIBezierPath {
guard size.width == size.height else {
fatalError(Constants.errorMessage)
}
let path = UIBezierPath()
let xAxis = origin.x
let yAxis = origin.y
let width = size.width
let height = size.height
path.move(to: CGPoint(x: xAxis + (width * 0.5), y: yAxis + 0))
path.addLine(to: CGPoint(x: xAxis + width, y: yAxis + height))
path.addLine(to: CGPoint(x: xAxis + 0, y: yAxis + height))
path.addLine(to: CGPoint(x: xAxis + width * 0.5, y: yAxis + 0))
return path
}
To create a composition of equilateral triangles
override func draw(_ rect: CGRect) {
var parentBound = self.bounds
for _ in 1 ... numberOfInstances {
let trianglePath = getEquilateralTrianglePath(forSize: parentBound.size, origin: parentBound.origin)
trianglePath.stroke(withColor: .blue, lineWidth: Constants.lineWidth)
let squarePath = getSquare(forEquilateralTriangle: parentBound.size, origin: parentBound.origin)
squarePath.stroke(withColor: .blue, lineWidth: Constants.lineWidth)
parentBound = squarePath.bounds
}
}
Get ready for SwiftUI - updates coming soon!
Please find the GitHub Repo