Drawing paths and custom shapes in SwiftUI

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

To draw paths and custom shapes in SwiftUI, you can use the Path and Shape types provided by the SwiftUI framework.

The Path type represents a geometric path in two-dimensional space, and it consists of a sequence of straight and curved line segments. You can create a Path by constructing a Path object and adding line segments and curves to it using methods such as move(to:), addLine(to:), and addCurve(to:control1:control2:).

The Shape type represents a geometric shape that can be drawn within a rectangular frame, and it is defined by a closure that takes a Path object and modifies it to create the desired shape. You can create a Shape by defining a closure that adds line segments and curves to a Path object and returning the Path object from the closure.

Here’s an example of how to create a custom shape in SwiftUI by defining a closure that modifies a Path object:

struct Triangle: Shape {
  func path(in rect: CGRect) -> Path {
    var path = Path()

    path.move(to: CGPoint(x: rect.midX, y: rect.minY))
    path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
    path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
    path.addLine(to: CGPoint(x: rect.midX, y: rect.minY))

    return path
  }
}

In this example, the Triangle struct conforms to the Shape protocol and defines a path(in:) method that takes a CGRect object and returns a Path object. The path(in:) method creates a Path object and adds line segments to it to create a triangle shape.

To use the Triangle shape, you can create an instance of the Triangle struct and use it as the shape parameter of a Shape view. For example:

Triangle()
  .fill(Color.red)
  .frame(width: 200, height: 200)

This will create a red triangle shape with a size of 200×200 points. You can customize the appearance of the shape further by using additional modifiers, such as stroke() and lineWidth(_:), to control the stroke and line width of the shape.



✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.