Skip to content

Instantly share code, notes, and snippets.

@MoussaHellal
Created January 23, 2024 11:51
Show Gist options
  • Save MoussaHellal/adc1601c90905842bfd0094813723396 to your computer and use it in GitHub Desktop.
Save MoussaHellal/adc1601c90905842bfd0094813723396 to your computer and use it in GitHub Desktop.
RingAnimation
//
// ContentView.swift
// Animating Cirlce
//
// Created by Moussa on 23/1/2024.
//
import SwiftUI
// USAGE
struct ContentView: View {
var body: some View {
VStack {
RingAnimation(color: .brown, strokeWidth: 10, frame: 150)
RingAnimation(color: .cyan, strokeWidth: 3, frame: 150)
RingAnimation(color: .red, strokeWidth: 8, frame: 150)
RingAnimation(color: .black, strokeWidth: 15, frame: 150)
}
}
}
//RING ANIMATION
struct RingAnimation: View {
@State private var circleStart: CGFloat = 0.4
@State private var circleEnd: CGFloat = 0.325
@State private var rotationDegree: Angle = .degrees(0)
private let animation = Animation.linear(duration: 3).delay(0.5)
private let trackerRotation: Double = 5
private let animationDuration: Double = 3
var color: Color
var strokeWidth: CGFloat
var frame: CGFloat
init(color: Color = .white, strokeWidth: CGFloat = 2, frame: CGFloat = 300) {
self.color = color
self.strokeWidth = strokeWidth
self.frame = frame
}
var body: some View {
createRing()
.frame(width: frame, height: frame)
.onAppear {
// YOU CAN THE DELAY YOU WANT IN HERE
animateLoader(delay: 0)
}
}
private func createRing() -> some View {
Circle()
.trim(from: circleStart, to: circleEnd)
.stroke(style: StrokeStyle(lineWidth: strokeWidth, lineCap: .round))
.fill(color)
.rotationEffect(rotationDegree)
}
private func getRotationAngle() -> Angle {
.degrees(360 * trackerRotation) + .degrees(120)
}
private func animateLoader(delay: Double) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
withAnimation(self.animation) {
self.rotationDegree = .degrees(-57.5)
self.circleEnd = 0.325
}
withAnimation(.easeInOut(duration: self.trackerRotation * self.animationDuration)) {
self.rotationDegree += self.getRotationAngle()
}
withAnimation(.easeInOut(duration: (self.trackerRotation * self.animationDuration) / 2.25)) {
self.circleEnd = 0.95
}
self.animateLoader(delay: self.trackerRotation * self.animationDuration)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment