Damiano Miazzi
Damiano Miazzi

Reputation: 2315

Draw line between 2 CGPoint without using to many addLine

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

Answers (2)

Raja Kishan
Raja Kishan

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

Sweeper
Sweeper

Reputation: 271605

You seem to have forgotten to stroke your line. filling 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

Related Questions