How to iterate over all segments/points of a Path of a Shape in SwiftUI?

Viewed 302

Let's say I have a Shape:

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.minX, y: rect.maxY))
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
        path.addLine(to: CGPoint(x: rect.midX, y: rect.minY))

        return path
    }
}

How can I get the Path of this Shape and iterate over all points of this path? This rectangle is just an example. I have a lot of different shapes with relative/absolute positions. For a specific use case I need to compare the points with a given point

I'm looking for something like:

public func checkPath(shape: Shape) {
    for point in shape.path {
        // do calculation
    }
}
1 Answers

SwiftUI Shape does not have own size, so you need to provide/request rect of area where shape will be used. So here is a demo of possible approach to go with:

public func checkPath<S: Shape>(shape: S, in rect: CGRect) {
    shape.path(in: rect).forEach { element in
        switch element {
            case .move(to: let point):
                print("Calculate here move to: \(point)")
            case .line(to: let point):
                print("Calculate here line to: \(point)")
            // .. handle other cases here
            default:
                print("Ignore unsupported")
        }
    }
}
Related