Hello,
I am trying to use the SwiftUI canvas and I'm having a couple of issues. One is that I'd like to be able to fit a canvas view in a ScrollView, but when the canvas is inside a ScrolLView, nothing draws. Additionally, I'm trying to draw lines on the canvas on Appear, but I can't seem to get that to work either. Below is a simplified version of the code I have:
struct Line: Codable, Hashable {
var points: [CGPoint]
var colorName: String?
var rgb: [Double]?
private enum CodingKeys: String, CodingKey {
case points
case colorName
case rgb
}
}
extension CGPoint: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
}
struct CanvasExample: View {
@State var lines: [Line] = []
@State var selectedColor: Color = Color.black
var body: some View {
Canvas { ctx, size in
for line in lines {
var path = Path()
path.addLines(line.points)
ctx.stroke(path, with: .color(line.color), style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))
}
}.gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local)
.onChanged({ value in
let position = value.location
if value.translation == .zero {
lines.append(Line(points: [position], color: selectedColor))
} else {
guard let lastIndex = lines.indices.last else {
return
}
lines[lastIndex].points.append(position)
}
})
)
.onAppear {
lines.append(Line(points: [position], color: .black))
}
}
}
Any help would be greatly appreciated. Thank you.