Created
August 24, 2019 10:12
-
-
Save filimo/27558c7f09b5474537b4fcda0a85f63e to your computer and use it in GitHub Desktop.
Random angular gradient animations in SwiftUI
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 | |
struct AngularGradientView2: View { | |
var body: some View { | |
return VStack { | |
CustomAngularGradientView() | |
} | |
.padding([.leading, .trailing], 30) | |
.animation(Animation.linear(duration: 1).repeatForever(autoreverses: false)) | |
} | |
} | |
struct CustomCircle: View { | |
@Binding var restart: Bool | |
@State var onMode: Bool = false | |
private func randomColor() -> Color { | |
let colors: [Color] = [.red, .yellow, .green, .blue, .purple, .orange] | |
let index = Int.random(in: 0...5) | |
return colors[index] | |
} | |
private func randomSpectrum() -> Gradient { | |
if(restart) {} | |
let colors = Array(0...5).map { _ in randomColor() } | |
return Gradient(colors: colors) | |
} | |
private func randomDash() -> CGFloat { | |
if(restart) {} | |
return CGFloat(Int.random(in: 1...50)) | |
} | |
private func randomDegrees() -> Angle { | |
if(restart) {} | |
return .degrees(Bool.random() ? 0 : 360) | |
} | |
var body: some View { | |
Circle() | |
.stroke(style: .init( | |
lineWidth: 40, | |
dash: [randomDash(), randomDash()], | |
dashPhase: onMode ? 0 : 1)) | |
.fill(AngularGradient(gradient: randomSpectrum(), center: .center)) | |
.rotationEffect(randomDegrees()) | |
.onAppear { | |
self.onMode = true | |
} | |
} | |
} | |
struct CustomAngularGradientView: View { | |
@State var restart = true | |
var body: some View { | |
ZStack { | |
CustomCircle(restart: $restart).aspectRatio(1/12, contentMode: .fit) | |
CustomCircle(restart: $restart).aspectRatio(1/5, contentMode: .fit) | |
CustomCircle(restart: $restart).aspectRatio(1/3.2, contentMode: .fit) | |
CustomCircle(restart: $restart) | |
CustomCircle(restart: $restart) | |
} | |
.onAppear { | |
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in | |
self.restart.toggle() | |
} | |
} | |
} | |
} | |
#if DEBUG | |
struct AngularGradientView2_Previews: PreviewProvider { | |
static var previews: some View { | |
AngularGradientView2() | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment