Home > Enterprise >  How can I animate changes to a BezierPath defined custom cornerRadius with SwiftUI?
How can I animate changes to a BezierPath defined custom cornerRadius with SwiftUI?

Time:11-14

I am using the following approach to add rounded corners to a view on x number of corners:

enter image description here

CodePudding user response:

The issue is in the RoundedCorner struct. It was not written with animations in mind. While a struct conforming to the Shape protocol is animatable, it won't animate without a var animatableData in it that provides the ability for the system to understand how to animate the Shape. I don't know why it isn't required to be implemented, because it is usually pretty trivial to do, as in this case.

Change your RoundedCorner struct to the following, and it will animate like you want it to:

struct RoundedCorner: Shape {

    var radius: CGFloat
    var corners: UIRectCorner
    var animatableData: CGFloat {
        get { return radius }
        set { radius = newValue }
    }

    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        return Path(path.cgPath)
    }
}

enter image description here

  • Related