animate scaling a rectangle from 0.5 to 1.5 in size forever in swiftui, using withanimation or animation(_:value:) in swift in swift

Here's an example of how to animate scaling a rectangle from 0.5 to 1.5 forever in SwiftUI using withAnimation:

main.swift
struct AnimatedRectangle: View {
    @State private var scale: CGFloat = 0.5
    
    var body: some View {
        Rectangle()
            .scaleEffect(scale)
            .foregroundColor(.blue)
            .animation(Animation.easeInOut(duration: 1).repeatForever())
            .onAppear {
                withAnimation {
                    self.scale = 1.5
                }
            }
    }
}
402 chars
16 lines

In this example, we use the scaleEffect modifier to scale the rectangle based on the scale state variable. We then use the animation modifier to specify the animation we want to run. We're using the easeInOut timing curve with a 1 second duration, and calling repeatForever to create an animation that loops indefinitely.

Finally, we use the onAppear modifier to trigger the animation by changing the scale state variable from 0.5 to 1.5 with the withAnimation closure.

You can also achieve this using the animation(_:value:) function. Here's an example:

main.swift
struct AnimatedRectangle: View {
    @State private var scale: CGFloat = 0.5
    
    var body: some View {
        Rectangle()
            .scaleEffect(scale)
            .foregroundColor(.blue)
            .animation(.easeInOut(duration: 1), value: scale)
            .onAppear {
                Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { _ in
                    withAnimation {
                        self.scale = self.scale == 0.5 ? 1.5 : 0.5
                    }
                }
            }
    }
}
527 chars
18 lines

In this example, we use the animation(_:value:) function to specify the animation and the scale state variable as the value that triggers the animation. We're also using a Timer to switch between the scale values of 0.5 and 1.5 every 2 seconds.

related categories

gistlibby LogSnag