Let us discuss this by completing a simple task using UIBezierPath in this article:
The composition of equilateral triangles alternating with squares. Aligning the Squares and equilateral triangles is straightforward, sum and multiplication should suffice.
For creating a shape or adding a line, we should go for 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.
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)
func square(from origin: CGPoint, side: CGFloat) -> UIBezierPath {
let path = UIBezierPath()
let x = origin.x
let y = origin.y
path.move(to: CGPoint(x: x, y: y))
path.addLine(to: CGPoint(x: x + side, y: y))
path.addLine(to: CGPoint(x: x + side, y: y + side))
path.addLine(to: CGPoint(x: x, y: y + side))
path.addLine(to: CGPoint(x: x, y: y))
path.close()
return path
}
func equilateralTriangle(from origin: CGPoint, side: CGFloat) -> UIBezierPath {
let path = UIBezierPath()
let x = origin.x
let y = origin.y
path.move(to: CGPoint(x: x, y: y))
path.addLine(to: CGPoint(x: x + side, y: y))
path.addLine(to: CGPoint(x: x + side/2, y: y - side))
path.addLine(to: CGPoint(x: x, y: y))
path.close()
return path
}
override func draw(_ rect: CGRect) {
var parentBounds = self.bounds
for _ in 1 ... numberOfInstances {
let equilateralTriangle = equilateralTriangle(from: parentBounds.origin, side: parentBounds.size.width)
equilateralTriangle.stroke(withColor: .blue, lineWidth: Constants.lineWidth)
let square = square(from: parentBounds.origin, side: parentBounds.size.width)
square.stroke(withColor: .blue, lineWidth: Constants.lineWidth)
parentBounds = square.bounds
}
}
Note
Please find the GitHub Repo
Get ready for SwiftUI - updates are coming soon!
This is a free third party commenting service we are using for you, which needs you to sign in to post a comment, but the good bit is you can stay anonymous while commenting.