-
-
Save sergeytimoshin/1dc887d0f51b0d18f7bdcbf4bd21e181 to your computer and use it in GitHub Desktop.
LinearGradient transition animation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
extension Color { | |
static func random()->Color { | |
let r = Double.random(in: 0 ... 1) | |
let g = Double.random(in: 0 ... 1) | |
let b = Double.random(in: 0 ... 1) | |
return Color(red: r, green: g, blue: b) | |
} | |
} | |
struct ContentView: View { | |
@State private var gradientA: [Color] = [.red, .purple] | |
@State private var gradientB: [Color] = [.red, .purple] | |
@State private var firstPlane: Bool = true | |
func setGradient(gradient: [Color]) { | |
if firstPlane { | |
gradientB = gradient | |
} | |
else { | |
gradientA = gradient | |
} | |
firstPlane = !firstPlane | |
} | |
@State private var selected = 0 | |
var body: some View { | |
ZStack { | |
LinearGradient(gradient: Gradient(colors: self.gradientA), startPoint: UnitPoint(x: 0, y: 0), endPoint: UnitPoint(x: 0, y: 1)) | |
LinearGradient(gradient: Gradient(colors: self.gradientB), startPoint: UnitPoint(x: 0, y: 0), endPoint: UnitPoint(x: 0, y: 1)) | |
.opacity(self.firstPlane ? 0 : 1) | |
TabView(selection: $selected) { | |
Text("☀️").font(.title).tag(0) | |
Text("🌦").font(.title).tag(1) | |
Text("⛈").font(.title).foregroundColor(Color.white).tag(2) | |
} | |
.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always)) | |
.tabViewStyle(PageTabViewStyle()) | |
.onChange(of: selected, perform: { value in | |
withAnimation(.spring()) { | |
self.setGradient(gradient: [Color.random(), Color.random()]) | |
} | |
}) | |
} | |
.edgesIgnoringSafeArea(.all) | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment