SwiftUI 利用AngularGradient來制作Loading的動畫
xcode 13.3.1, swift 5.5, iOS 15.4
2022-08-10
Loading的動畫在很多地方都會用到,這篇我們會講講怎樣用SwiftUI AngularGradient和結合Animation簡單的創建Loading的動畫。
1. 首先先畫一個寬度為40的藍色的部份圓圈
struct AngularGradientCircleExample : View {
var body: some View {
Circle()
.inset(by: 20.0)
.stroke(.blue, lineWidth: 40)
}
}
2. 使用AngularGradient來制作一個漸變的藍色。
struct AngularGradientCircleExample : View {
let style = AngularGradient(
colors: [.white,.white,.white,.white,.blue,],
center: .center,
startAngle: Angle(degrees: 0.0),
endAngle: Angle(degrees: 360.0)
)
var body: some View {
Circle()
.inset(by: 20.0)
.stroke(style, lineWidth: 40)
}
}
3. 使用rotationEffect來改變角度。
struct AngularGradientCircleExample : View {
let style = AngularGradient(
colors: [.white,.white,.white,.white,.blue,],
center: .center,
startAngle: Angle(degrees: 0.0),
endAngle: Angle(degrees: 360.0)
)
var body: some View {
Circle()
.inset(by: 20.0)
.stroke(style, lineWidth: 40)
.rotationEffect(.degrees(30))
}
}
4. 使用animation來改變degree就可以做成一個旋轉的動畫。
struct AngularGradientCircleExample : View {
let style = AngularGradient(
colors: [.white,.white,.white,.white,.blue,],
center: .center,
startAngle: Angle(degrees: 0.0),
endAngle: Angle(degrees: 360.0)
)
@State var runAnimation = false
var body: some View {
Circle()
.inset(by: 20.0)
.stroke(style, lineWidth: 40)
.rotationEffect(.degrees(runAnimation ? 360.0 : 0.0))
.animation(.linear(duration: 3.0).repeatForever(autoreverses: false), value: runAnimation)
.onTapGesture {
runAnimation = true
}
}
}