SwiftUI Circlar Progress Bar

Code

circle

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import SwiftUI

struct ChargeNormalView: View {
    
    private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    
    var width: CGFloat = 200
    // you can comment on this line of code, so funny
    var color1 = #colorLiteral(red: 0.2078431487, green: 0.56745098062, blue: 0.5333333433, alpha: 1)
    var color2 = #colorLiteral(red: 0.6078431487, green: 0.06745098062, blue: 0.5333333433, alpha: 1)
        
    @State var percent: CGFloat = 0
    
    var body: some View {
        let mutiplier = width / 44
        let progress = 1 - percent / 100
        
        return ZStack {
            Circle()
                .stroke(Color.black.opacity(0.1),
                        style: StrokeStyle(lineWidth: 5 * mutiplier))
                .frame(width: width, height: width)
            
            Circle()
                .trim(from: progress, to: 1)
                .stroke(
                    LinearGradient(gradient: Gradient(colors: [Color(color1), Color(color2)]), startPoint: .topLeading, endPoint: .bottomTrailing),
                    style: StrokeStyle(lineWidth: 5 * mutiplier, lineCap: .round, lineJoin: .round)
            )
                .rotationEffect(Angle(degrees: 90))
                .rotation3DEffect(Angle(degrees: 180), axis: (x: 1, y: 0, z: 0))
                .frame(width: width, height: width)
                .shadow(color: Color(color1).opacity(0.1), radius: 3, x: 0, y: 3)
            Text("\(Int(percent))%")
                .font(.system(size: 14 * mutiplier))
                .fontWeight(.bold)
                .onReceive(timer) { time in
                    
                    if percent >= 100 {
                        percent = 100
                        // need cancel timer
                        self.timer.upstream.connect().cancel()
                    } else {
                        percent += 10
                    }
                    print("The time is now \(time)")
                }
        }
    }
}

Preview

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy