How to combine rotation and fade-out animation in SwiftUI
In this tutorial, we will see how to combine rotation and fade-out animation in SwiftUI.
We can combine rotation and fade-out animations using the rotationEffect
and opacity
modifiers.
TheĀ rotationEffect
modifier is used to rotate a view by a specified angle, and opacity
modifier is used to adjust the transparency of a view.
Example
import SwiftUI struct ContentView: View { @State private var isAnimating = false var body: some View { VStack { Image(systemName: "star.fill") .font(.system(size: 100)) .foregroundColor(.mint) // Rotation effect based on the state variable isAnimating .rotationEffect(Angle(degrees: isAnimating ? 360 : 0)) // Opacity effect based on the state variable isAnimating .opacity(isAnimating ? 0 : 1) // Tap gesture to trigger the animation .onTapGesture { // Animation block with linear easing, repeating forever without reversing withAnimation(Animation.linear(duration: 2).repeatForever(autoreverses: false)) { self.isAnimating.toggle() } } } } }
The above code will display a mint-colored star that will rotate continuously when we tap on it. The symbol will also fade based on its animation state controlled by the isAnimating
variable.
Output:
Now, if we want to reverse the rotation after completing one cycle, we can simply do that by setting the autoreverses
to true
instead of false
.
autoreverses: true
The above code will allow the symbol to rotate in both directions with fade in and out accordingly.
Example
import SwiftUI struct ContentView: View { @State private var isAnimating = false var body: some View { VStack { Image(systemName: "star.fill") .font(.system(size: 100)) .foregroundColor(.mint) // Rotation effect based on the state variable isAnimating .rotationEffect(Angle(degrees: isAnimating ? 360 : 0)) // Opacity effect based on the state variable isAnimating .opacity(isAnimating ? 0 : 1) // Tap gesture to trigger the animation .onTapGesture { // Animation block with linear easing, repeating forever with reversing withAnimation(Animation.linear(duration: 2).repeatForever(autoreverses: false)) { self.isAnimating.toggle() } } } } }
The above code will rotate the symbol and fade out continuously, and when it completes one cycle (360-degree rotation), it will reverse itself.
So, it will rotate from 0 to 360 degrees and then back from 360 to 0 degrees, and the opacity will fade in and out accordingly.
Output:
Leave a Reply