One thing I have noticed is the Canvas code doesn't run until there's a gesture, and I'm not sure why that is because the documentation has an example that displays a drawing upon loading the Canvas.
struct Line {
var points: [CGPoint]
var color: Color
}
var body: some View {
@State var lines: [Line] = []
Canvas { ctx, size in
for line in lines {
let color = line.colorName == nil ? getColor(colorName: nil, rgb: line.rgb) : getColor(colorName: line.colorName, rgb: nil)
var path = Path()
print(line.points) // this is how I noticed this code doesn't run until the gesture runs. This print statement doesn't run upon loading the Canvas
path.addLines(line.points)
ctx.stroke(path, with: .color(color), style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))
}
}
.gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local)
.onChanged({ value in
draw(position: value.location, translation: value.translation)
}
})
)
.onAppear {
lines = parseLinesString()
for line in lines {
for point in line.points {
draw(position: point, translation: nil)
}
}
}
func draw(position: CGPoint, translation: CGSize?) {
if translation == .zero || translation == nil {
lines.append(Line(points: [position], color: color.black))
} else {
guard let lastIndex = lines.indices.last else {
return
}
lines[lastIndex].points.append(position)
unsaved = true
}
}
}
As I mentioned previously, I'm not sure how to translate the documentation example to my application. If anyone could point me in the right direction that would be greatly appreciated. Thank you.