GarySabo
GarySabo

Reputation: 6680

How to animate a circle to fill instead of using .trim?

I have this ring style view below, this animation starts at a filled ring of 100% and "unfills" to the trim amount, I'd like to reverse the animation so it starts at 0 and fills to the trim amount.

var progressAnimation: Animation {
        Animation
            .linear
            .speed(0.5)
            .delay(0.2)
     }
    
    var body: some View {
        VStack {
            ZStack {
                Circle()
                    .stroke(Color(.systemFill).opacity(0.5), style: StrokeStyle(lineWidth: lineWidth))
                    .frame(height: 125)
                Circle()
                    .trim(from: CGFloat(getTrimLevelForRingFromExertionLevel()), to: 1)
                    .stroke(ColorManager.getColorsForMetric(metricType: .Exertion(value: mostRecentEffortLevelObject?.effortLevel ?? 0)),
                        style: StrokeStyle(lineWidth: lineWidth, lineCap: .round, lineJoin: .round, miterLimit: .infinity, dash: [20, 0], dashPhase: 0))
                    .animation(self.progressAnimation, value: getTrimLevelForRingFromExertionLevel())
                    .rotationEffect(Angle(degrees: 90))
                    .rotation3DEffect(Angle(degrees: 180), axis: (x: 1, y: 0, z: 0))
                    .frame(height: 125)

Upvotes: 1

Views: 474

Answers (1)

Asperi
Asperi

Reputation: 257663

Probably you have issue in different code or model, because approach in referenced answer works fine.

Here is a complete demo. Tested with Xcode 12.4 / iOS 14.4

demo

struct DemoView: View {
    @State private var progress = 0.0
    var body: some View {
        VStack {
            Circle()
                 .trim(from: 0.0, to: CGFloat(min(self.progress, 1.0)))
                 .stroke(Color.blue ,style: StrokeStyle(lineWidth: 25.0, lineCap: .round, lineJoin: .round))
                 .animation(.linear, value: progress)
                 .rotationEffect(Angle(degrees: 270.0))
                 .onAppear {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                        progress = 0.73
                    }
            }
        }.padding()
    }
}

Upvotes: 1

Related Questions