Skip to content

Instantly share code, notes, and snippets.

@PetreVane
Created April 1, 2020 09:25
Show Gist options
  • Save PetreVane/971788d2399b79063ba2990a0eeeda89 to your computer and use it in GitHub Desktop.
Save PetreVane/971788d2399b79063ba2990a0eeeda89 to your computer and use it in GitHub Desktop.
Creates rectangles, triangles and ovals
extension CAShapeLayer {
static func rectangle(roundedRect: CGRect, cornorRadius: CGFloat, color: UIColor) -> CAShapeLayer {
let path = UIBezierPath(roundedRect: roundedRect, cornerRadius: cornorRadius)
let shape = CAShapeLayer()
shape.path = path.cgPath
shape.fillColor = color.cgColor
return shape
}
}
// Secondly, in order to display the rectangle in a UIView instance, it is necessary to write another extension of UIView.
extension UIView {
func draw(_ shapes: CAShapeLayer...) {
for shape in shapes {
layer.addSublayer(shape)
}
}
}
// Then, let’s put them together and see the outcome.
let containFrame = CGRect(x: 0, y: 0, width: 500, height: 500)
let containView = UIView(frame: containFrame)
containView.backgroundColor = .white
let roundedRect = containFrame.insetBy(dx: 100, dy: 100)
containView.draw(
.rectangle(roundedRect: roundedRect, cornorRadius: 16, color: .red)
)
// Now, we are able to create ovals, triangles, and lines with the same pattern.Add the following code into the extension of CAShapeLayer.
extension CAShapeLayer {
// ...
static func oval(in rect: CGRect, color: UIColor) -> CAShapeLayer {
let path = UIBezierPath(ovalIn: rect)
let shape = CAShapeLayer()
shape.path = path.cgPath
shape.fillColor = color.cgColor
return shape
}
static func triangle(_ point1: CGPoint, _ point2: CGPoint, _ point3: CGPoint, color: UIColor) -> CAShapeLayer {
let path = UIBezierPath()
path.move(to: point1)
path.addLine(to: point2)
path.addLine(to: point3)
path.close()
let shape = CAShapeLayer()
shape.path = path.cgPath
shape.fillColor = color.cgColor
return shape
}
static func line(start: CGPoint, end: CGPoint, width: CGFloat, color: UIColor) -> CAShapeLayer {
let path = UIBezierPath()
path.move(to: start)
path.addLine(to: end)
let shape = CAShapeLayer()
shape.path = path.cgPath
shape.lineWidth = width
shape.strokeColor = color.cgColor
return shape
}
}
// Finally, the drawing code will look like this.
containView.draw(
.rectangle(roundedRect: roundedRect, cornorRadius: 16, color: .red),
.oval(in: roundedRect.insetBy(dx: 20, dy: 30), color: .blue),
.triangle(CGPoint(x: 10, y: 10), CGPoint(x: 10, y: 150), CGPoint(x: 150, y: 10), color: .brown),
.line(start: CGPoint(x: 480, y: 10), end: CGPoint(x: 480, y: 300), width: 6, color: .green)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment