forever change scale of rectangle from 0.5 to 1.5 as long as it is visible in swiftui in swift

You can use the scaleEffect modifier in SwiftUI to change the scale of a Rectangle view. To animate the change, you can wrap the modifier in an animation block. To make the scale change continuously, you can wrap the Rectangle view in a while loop and use a @State variable to toggle a Bool value that starts and stops the animation.

Here is an example code that changes the scale of the rectangle from 0.5 to 1.5 and back to 0.5, and so on:

main.swift
import SwiftUI

struct ContentView: View {
    @State private var isAnimating = true
    
    var body: some View {
        VStack {
            while isAnimating {
                Rectangle()
                    .fill(Color.blue)
                    .frame(width: 100, height: 100)
                    .scaleEffect(0.5)
                    .animation(Animation.easeInOut(duration: 1).repeatForever())
                    .onDisappear {
                        self.isAnimating = false
                    }
            }
        }
    }
}
540 chars
21 lines

In this example, the Rectangle is wrapped in a VStack so that it takes up the entire screen. The scaleEffect modifier changes the scale of the rectangle to 0.5. The animation block makes the scale change gradually using an ease-in-out animation, and repeats the animation forever. The onDisappear modifier toggles the isAnimating variable to false when the view disappears (in this case, when the app is closed).

You can modify the parameters of the Animation and scaleEffect modifiers to adjust the duration and style of the animation, and the size of the rectangle.

related categories

gistlibby LogSnag