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

You can use the withAnimation function or Animation struct to animate the scaling of a rectangle from 0.5 to 1.5 size.

Here's an example using withAnimation:

main.swift
struct ContentView: View {
    @State private var scale: CGFloat = 0.5

    var body: some View {
        Rectangle()
            .frame(width: 100, height: 100)
            .scaleEffect(scale)
            .onTapGesture {
                withAnimation {
                    self.scale = 1.5
                }
            }
    }
}
331 chars
15 lines

In this example, the scale property of the rectangle is updated when the user taps on it. The withAnimation function wraps the code that updates the property, which causes the animation to occur. The default animation duration and easing function are used.

Alternatively, you can use the animation modifier to specify a custom animation:

main.swift
struct ContentView: View {
    @State private var scale: CGFloat = 0.5

    var body: some View {
        Rectangle()
            .frame(width: 100, height: 100)
            .scaleEffect(scale)
            .animation(.easeInOut(duration: 1.0))
            .onTapGesture {
                self.scale = 1.5
            }
    }
}
327 chars
14 lines

In this example, the .animation modifier specifies a custom animation that eases in and out over a duration of 1 second. The .scaleEffect modifier is used to update the size of the rectangle, and the onTapGesture closure updates the scale property to trigger the animation.

related categories

gistlibby LogSnag