How to create a path with look in swiftUI?

By | January 22, 2024

In SwiftUI, you can create a path with a custom shape by using the Path and Shape types. Here’s a basic example of how to create a custom path with a shape in SwiftUI:

import SwiftUI

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

        // Create a custom shape using moveTo, addLine, addQuadCurve, etc.
        path.move(to: CGPoint(x: rect.width / 2, y: 0))
        path.addLine(to: CGPoint(x: rect.width, y: rect.height))
        path.addLine(to: CGPoint(x: 0, y: rect.height))
        path.closeSubpath()

        return path
    }
}

struct ContentView: View {
    var body: some View {
        CustomShape()
            .fill(Color.blue)
            .frame(width: 200, height: 200)
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

In this example:

  • We define a custom shape CustomShape that conforms to the Shape protocol.
  • The path(in:) function is where you define the shape using Path methods like move(to:), addLine(to:), addQuadCurve(to:control:), etc.
  • In the ContentView, we create an instance of CustomShape and apply some styling, such as filling it with a blue color and setting its frame size.

You can modify the path(in:) function to create different custom shapes based on your requirements. SwiftUI provides a variety of path-building functions, allowing you to create complex shapes and paths easily.

If you want to create more complex shapes or paths, you might also consider using the Path and CGPoint directly without a separate Shape structure.

Leave a Reply

Your email address will not be published. Required fields are marked *