Color Animation in SwiftUI

DevTechie Inc
Jun 24, 2022


Photo by Lucas Kapla on Unsplash

One of the animatable property in SwiftUI is Color.

When animation modifier is applied on color, view transitions from one color to other transitioning through colors in between. An example will help to understand better.

Color change without animation

struct ColorAnimationInSwiftUI: View {
    
    @State private var animate = false
    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 20)
                .fill(animate ? Color.orange : Color.gray.opacity(0.4))
            Text("DevTechie")
                .font(.largeTitle)
                .foregroundColor(.white)
        }
        .frame(width: 300, height: 300)
        .onTapGesture {
            animate.toggle()
        }
    }
}
Color change with Animation

struct ColorAnimationInSwiftUI: View {
    
    @State private var animate = false
    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 20)
                .fill(animate ? Color.orange : Color.gray.opacity(0.4))
            Text("DevTechie")
                .font(.largeTitle)
                .foregroundColor(.white)
        }
        .frame(width: 300, height: 300)
        .onTapGesture {
            animate.toggle()
        }
        .animation(.easeInOut, value: animate)
    }
}
Animation Speed:

We can use animation’s speed function to control the speed of animation. We will set speed to takes double as input parameter and returns an animation that has its speed multiplied by the supplied value. For example, if we want to reduce speed by 25% for one second long animation then the animation will play 25% of the normal speed or in other words animation which would have taken a second to complete will now take 4 seconds.

struct ColorAnimationInSwiftUI: View {
    
    @State private var animate = false
    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 20)
                .fill(animate ? Color.orange : Color.gray.opacity(0.4))
            Text("DevTechie")
                .font(.largeTitle)
                .foregroundColor(.white)
        }
        .frame(width: 300, height: 300)
        .onTapGesture {
            animate.toggle()
        }
        .animation(Animation.easeInOut.speed(0.25), value: animate)
    }
}


With that we have reached the end of this article. Thank you once again for reading. Subscribe to our weekly newsletter at https://www.devtechie.com