How do I draw with Canvas and Shapes?

In Swift, you can create beautiful drawings using the Canvas and Shapes features provided by the SwiftUI framework. Here’s a simple example of how to draw various shapes like rectangles, circles, and lines within a Canvas view.

// Example of drawing shapes with SwiftUI import SwiftUI struct ContentView: View { var body: some View { Canvas { context, size in // Draw a rectangle context.fill(Rectangle().path(in: CGRect(x: 20, y: 20, width: 100, height: 100)), with: .color(.blue)) // Draw a circle context.fill(Circle().path(in: CGRect(x: 150, y: 20, width: 100, height: 100)), with: .color(.red)) // Draw a line context.stroke(Line(from: CGPoint(x: 20, y: 150), to: CGPoint(x: 200, y: 150)), with: .color(.green), lineWidth: 5) } .frame(width: 300, height: 300) } } struct Line: Shape { var from: CGPoint var to: CGPoint func path(in rect: CGRect) -> Path { var path = Path() path.move(to: from) path.addLine(to: to) return path } } // Don't forget to set ContentView as the main view in your App struct.

Swift SwiftUI Canvas Drawing Shapes Rectangles Circles Lines