top of page
Writer's pictureHui Wang

62. SwiftUI: Introducing Path

Today I will show you how to use Path.

Path can draw highly complex graphics, and I'm just showing its basic functions here.


Steps:

  • First, add a Path, define the Path shape in the closure

  • Move the coordinates of Path to {50, 0}

  • Draw a line from the starting point of Path through the addLine method to {50, 200}

  • Then draw a line to the right from {50, 200} to {250, 200}

var body: some View {
    Path { path in
        path.move(to: CGPoint(x: 50, y: 0))
        path.addLine(to: CGPoint(x: 50, y: 200))
        path.addLine(to: CGPoint(x: 250, y: 200))
    }
}

  • Continue to draw a straight line upwards to {250, 0}

  • This way, we get a square Path of size 250x250.

path.addLine(to: CGPoint(x: 250, y: 0))

  • Then draw another Path and move the new starting point to {50, 300}

  • Then use addQuadCurve to draw a Bezier curve to {250, 300}, control point to {150, 450}

  • Add another Bezier curve in the same way to {350, 300}, control point to {300, 220}

path.move(to: CGPoint(x: 50, y: 300))
path.addQuadCurve(to: CGPoint(x: 250, y: 300),
                  control: CGPoint(x: 150, y: 450))
path.addQuadCurve(to: CGPoint(x: 350, y: 300),
                  control: CGPoint(x: 300, y: 220))

  • Then add a stroke effect to the Path and set the lineWidth to 8. In this case, the fill color of all paths will disappear.

.stroke(lineWidth: 8)


In addition to using Path to draw straight lines or curves, you can also use Path to draw typical graphics such as ellipses and rectangles.

  • Add a new Path.

  • Use addEllipse to draw an ellipse/circle, parameters: x: 90, y: 50, width: 200, height: 200

path.addEllipse(in: CGRect(x: 90, y: 50, width: 200, height: 200))

  • Use addRoundedRect to draw a rectangle with rounded corners.

path.addRoundedRect(in: CGRect(x: 90, y: 50, width: 200, height: 200), cornerSize: CGSize(width: 32, height: 32))

 

Follow me on:

Comments


bottom of page