Skip to content

Instantly share code, notes, and snippets.

@eschmar
Created February 27, 2023 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eschmar/063649100e768da563664f3ab063de6d to your computer and use it in GitHub Desktop.
Save eschmar/063649100e768da563664f3ab063de6d to your computer and use it in GitHub Desktop.
SwiftUI gradient along a circular path animation
//: A SwiftUI based playground.
import SwiftUI
import PlaygroundSupport
struct MyShape : Shape {
var startAngle: Double
var progress: Double
func path(in rect: CGRect) -> Path {
var p = Path()
p.addArc(
center: CGPoint(x: 160, y:160),
radius: 80,
startAngle: .degrees(startAngle),
endAngle: .degrees(startAngle + progress),
clockwise: false
)
return p.strokedPath(.init(lineWidth: 60, lineCap: .round))
}
var animatableData: Double {
get { progress }
set { progress = newValue }
}
}
struct MyExperimentalView: View {
@State var startAngle: Double = 30.0
@State var progress: Double = 10.0
var body: some View {
ZStack {
Color.purple
/// Shape with gradient along path
MyShape(
startAngle: startAngle,
progress: progress
)
.foregroundColor(.white)
.mask {
AngularGradient(
gradient: Gradient(colors: [.clear, .white]),
center: .center,
startAngle: .degrees(startAngle - 15.0),
endAngle: .degrees(startAngle + progress + 15.0)
/// ^-- Increase gradient range slightly to include the rounded tips
)
}
/// Outline
MyShape(startAngle: startAngle, progress: progress)
.stroke(Color.white, lineWidth: 4)
.opacity(0.0)
}.frame(width: 320, height: 320).onAppear {
withAnimation(.linear(duration: 2.0).repeatForever(autoreverses: true)) {
progress = 310.0
}
}
}
}
let view = MyExperimentalView()
PlaygroundPage.current.setLiveView(view)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment