Reputation: 2315
I'am trying in SwiftUI to draw a line between to CGPoint(x:0, y:0)
, CGPoint(x:100, y:100)
struct Line : Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 0, y: 100))
path.addLine(to: CGPoint(x: 5, y: 100))
path.addLine(to: CGPoint(x: 5, y: 0))
return path
}
}
struct GpsView: View {
var body: some View {
Line()
.fill(Color.red)
.frame(width: 300, height: 300)
}
}
Is there any way around easiest instead to specify 4 CGPoint
, something where I can just say from point 1 to point 2? Thanks.
Upvotes: 2
Views: 1234
Reputation: 18924
Use stroke
and fill
property.
struct Line : Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 100, y: 100))
return path
}
}
struct GpsView: View {
var body: some View {
Line()
.stroke(lineWidth: 5.0)
.fill(Color.red)
.frame(width: 300, height: 300)
}
}
Upvotes: 3
Reputation: 271605
You seem to have forgotten to stroke
your line. fill
ing the line fills the region enclosed by the line, which is why you always need 4 points.
You just need 2 points:
struct Line : Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 100, y: 100))
return path
}
}
Usage (this is where you stroke
):
Line()
.stroke(Color.red, lineWidth: 5)
.frame(width: 300, height: 300)
Upvotes: 2