Home > Net >  Add animated transition between gradient background change in SwiftUI
Add animated transition between gradient background change in SwiftUI

Time:01-19

I have this code below

import SwiftUI

struct MyUIView: View {
    
    let timer = Timer.publish(every: 0.6, on: .main, in: .common).autoconnect() 
    @State var gradientBackgroundArray = [Constants.gradientFirst, Constants.gradientSecond, Constants.gradientThird]
    
    var body: some View{
        HStack(){
            ZStack(){}
                .frame(maxWidth: .infinity, maxHeight: 20)
                .background(gradientBackgroundArray[0].animation(.easeInOut(duration: 0.4)))
            Spacer()
            ZStack(){}
                .frame(maxWidth: .infinity, maxHeight: 20)
                .background(gradientBackgroundArray[0].animation(.easeInOut(duration: 0.4)))
            Spacer()
            ZStack(){}
                .frame(maxWidth: .infinity, maxHeight: 20)
                .background(gradientBackgroundArray[0].animation(.easeInOut(duration: 0.4)))
        }
        .padding(10)
        .onReceive(timer){ _ in
            gradientBackgroundArray.shuffle()
        }
    }
    
}

class Constants {
    public static let gradientFirst = LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .leading, endPoint: .trailing)
    public static let gradientSecond = LinearGradient(gradient: Gradient(colors: [.black, .yellow]), startPoint: .leading, endPoint: .trailing)
    public static let gradientThird = LinearGradient(gradient: Gradient(colors: [.green, .white]), startPoint: .leading, endPoint: .trailing)
}

Now I shuffle gradientBackgroundArray every 0.6sec and it works fine. But the issue is that I want to add animation or transition effect to the background change after shuffling the values using this line of code:

.background(gradientBackgroundArray[2].animation(.easeInOut(duration: 0.4)))

But there's no animation or transition effect, it just changes instantly.

Please how can I achieve this?

CodePudding user response:

In SwiftUI you can’t easily animate from one set of colours to another.

You can animate the startPoint and endPoint, or the grayScale, saturation, or hueRotation, using one these modifiers…

.grayscale(_ amount: Double)
.hueRotation(_ angle: Angle)
.saturation(_ amount: Double)

If you want to animate the colours themselves, you'll need to create an AnimatableModifier, a full implementation of which can be found here.

  • Related