SwiftUI freeform drawing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct DrawingPath { | |
private var points = [CGPoint]() | |
private var breaks = [Int]() | |
mutating func addPoint(_ point: CGPoint) { | |
points.append(point) | |
} | |
mutating func addBreak() { | |
breaks.append(points.count) | |
} | |
var path: Path { | |
var path = Path() | |
guard let firstPoint = points.first else { return path } | |
path.move(to: firstPoint) | |
for i in 1..<points.count { | |
if breaks.contains(i) { | |
path.move(to: points[i]) | |
} else { | |
path.addLine(to: points[i]) | |
} | |
} | |
return path | |
} | |
} | |
struct DrawShape: Shape { | |
let drawingPath: DrawingPath | |
func path(in rect: CGRect) -> Path { | |
drawingPath.path | |
} | |
} | |
struct DrawViewTest: View { | |
@State private var drawing: DrawingPath | |
var body: some View { | |
ZStack { | |
Color.white // drawing background | |
DrawShape(drawingPath: drawing) | |
.stroke(lineWidth: 5) // define stroke width | |
.foregroundColor(.blue) // define stroke color | |
}.gesture(DragGesture() | |
.onChanged( { value in | |
drawing.addPoint(value.location) | |
}).onEnded( { value in | |
drawing.addBreak() | |
})) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment