-
Notifications
You must be signed in to change notification settings - Fork 0
/
SquareViewController.swift
63 lines (53 loc) · 1.92 KB
/
SquareViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//
// SquareViewController.swift
// UIKit CGPath
//
// Created by Luiz Pedro Franciscatto Guerra on 21/07/22.
//
import UIKit
class SquareViewController: UIViewController {
weak var squareView: UIView?
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
squareView?.center = self.view.center
}
override func viewDidLoad() {
super.viewDidLoad()
// Sets up the square
let square = SquareView(frame: CGRect(
origin: .zero,
size: CGSize(width: 100, height: 100)))
// The sttribute declaration is in another line
// so the weak reference doesn't get removed from memory
self.view.addSubview(square)
self.squareView = square
}
}
class SquareView: UIView {
override func draw(_ rect: CGRect) {
// Retrieving the core graphics context so you can draw in it
guard let context = UIGraphicsGetCurrentContext() else { return }
context.saveGState()
// Relasing the context when finished
// It's not necessary to do like this, you can just add the
// ```context.restoreGState()```
// at the end of the function
defer {
context.restoreGState()
}
// Creates a new empty path in a graphics context
context.beginPath()
// Drawing stages
context.move(to: .zero)
context.addLine(to: CGPoint(x: rect.width, y: 0))
context.addLine(to: CGPoint(x: rect.width, y: rect.height))
context.addLine(to: CGPoint(x: 0, y: rect.height))
context.addLine(to: .zero)
// Finishes the path
// This allows to draw more shapes in the same view
context.closePath()
// Sets the filling color that the path should be rendered with
context.setFillColor(UIColor.tintColor.cgColor)
context.fillPath()
}
}