Sergio Bost
Sergio Bost

Reputation: 3239

Best way to center a custom shape inside of a parent view?

enter image description here

I think the picture says it all. The view itself is centered, but since the shape does not fill the entire frame, the shape isn't centered. My question is simply what is the best approach to fix this.

Here is the relevant code, (its just a simple square)

    struct FilterShape: Shape {
    //Modeled from 60inches being maximum or 100%
    let width: CGFloat
    let height: CGFloat
    var widthPercentage: CGFloat {
        width / 60
    }
    var heightPercentage: CGFloat {
        height / 60
    }
    let isSquare: Bool
    func path(in rect: CGRect) -> Path {
        var path = Path()
        if !isSquare {
        path.move(to: CGPoint(x: rect.minX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.maxX * widthPercentage, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.maxX * widthPercentage, y: rect.maxX * heightPercentage))
        path.addLine(to: CGPoint(x: rect.minX, y: rect.maxX * heightPercentage))
        path.closeSubpath()
        } else {
            path.move(to: CGPoint(x: rect.minX, y: rect.minY))
            path.addLine(to: CGPoint(x: rect.maxX * widthPercentage, y: rect.minY))
            path.addLine(to: CGPoint(x: rect.maxX * widthPercentage, y: rect.maxX * widthPercentage))
            path.addLine(to: CGPoint(x: rect.minX, y: rect.maxX * widthPercentage))
            path.closeSubpath()
        }
        return path
    }
}

Upvotes: 0

Views: 329

Answers (1)

Sergio Bost
Sergio Bost

Reputation: 3239

This is my current workaround.

return path.offsetBy(dx: rect.width * 0.17, dy: rect.height * 0.17)

Offsetting the final path (by a number I experimented with to get) gave me this result:

enter image description here

which will work but will overshoot the parents frame under certain conditions

Upvotes: 0

Related Questions