swiftui animate circle in swift

To animate a circle in SwiftUI, we can use the ViewModifier protocol to create a custom modifier that applies the animation to the circle view. Here is an example of how to animate a circle with an ease in/out animation:

main.swift
struct CircleAnimation: ViewModifier {
    @State private var animationProgress: Double = 0.0
    
    func body(content: Content) -> some View {
        content
            .scaleEffect(CGFloat(animationProgress))
            .onAppear {
                withAnimation(Animation.easeInOut(duration: 2.0).repeatForever()) {
                    animationProgress = 1.0
                }
            }
    }
}

struct ContentView: View {
    var body: some View {
        Circle()
            .fill(Color.blue)
            .frame(width: 100, height: 100)
            .modifier(CircleAnimation())
    }
}
601 chars
23 lines

In the CircleAnimation modifier, we create a @State variable animationProgress to store the animation progress. We then modify the view with a scaleEffect based on the animation progress. On onAppear we start a easeInOut animation with a duration of 2 seconds that repeats forever. Inside the animation block, we update the animationProgress state variable to trigger the animation.

Finally, in the ContentView, we create a circle view and apply our CircleAnimation modifier to it with the .modifier() function. The resulting circle will scale in and out with a smooth ease in/out effect.

gistlibby LogSnag