42 - Use Animated Images in SwiftUI

Animations add life to any static image and can make the user interface more engaging and interactive. SwiftUI makes it easy to animate images with the help of the Image view and its built-in animation features.

To create animations in SwiftUI, you can use the withAnimation function along with the desired animation type, duration and other parameters. This function allows you to animate state transitions, which subsequently animates the affected views. You can trigger these animations based on certain conditions or events, such as when a view appears on the screen.

For example, you might animate an image scaling up and down by applying the scaleEffect modifier in response to a state variable change, which is then animated within a withAnimation block, like so:

struct ContentView: View {
  @State private var isAnimating = false

  var body: some View {
    Image("HelloHedgy")
      .resizable()
      .scaledToFit()
      .scaleEffect(isAnimating ? 1.5 : 1.0)
      .onAppear() {
        withAnimation(.easeInOut(duration: 1.0).repeatForever(autoreverses: true)) {
          isAnimating = true
        }
      }
  }
}

The preview should look as follows:

You can easily animate images in SwiftUI.

Here’s how this code works:

Using this approach, we can create various types of animations for images, including rotations, fades and translations. We can also combine multiple animations together and create complex animations that can dynamically change with user interactions.

In conclusion, animated images are a powerful tool to create dynamic and interactive user interfaces in SwiftUI. With its easy-to-use animation features, SwiftUI makes it possible to create stunning animations that engage users and enhance the user experience.