Drawing using the Canvas API
One of the most powerful features of UIKit is the possibility of creating a subclass of UIView, where we can draw directly into the graphic context using Core Graphic Framework's functions.SwiftUI implemented this functionality similarly via the Canvas view, where we can draw directly in the Core Graphic's context.In this recipe, we will explore the Canvas View by implementing a simple app to draw, using our finger.
Getting ready
Let's implement a SwiftUI app called Drawing.
How to do it…
The app will use a struct as a model to save the touches. Then, each model will be used to draw a line in a Canvas View. To do this, follow these steps:
- First, create the Line struct model and add a @State property to the main view, storing the lines we will be drawing:
struct Line {
var points: [CGPoint]
}
struct ContentView: View {
@State var lines: [Line] = []
var body: some View {
}
}
- In the body of the ContentView...