Skip to content

Instantly share code, notes, and snippets.

@alsedi
Last active September 27, 2020 21:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alsedi/db0d5a17c828dd3480db20de4eca1ee4 to your computer and use it in GitHub Desktop.
Save alsedi/db0d5a17c828dd3480db20de4eca1ee4 to your computer and use it in GitHub Desktop.
circular-indicator-full.swift
import UIKit
class ViewController: UIViewController {
let progressShape = CAShapeLayer()
let backgroundShape = CAShapeLayer()
let percent = 50.0
override func viewDidLoad() {
super.viewDidLoad()
view.layer.addSublayer(backgroundShape)
view.layer.addSublayer(progressShape)
updateIndicator(with: 0)
}
func updateIndicator(with percent: Double, isAnimated: Bool = false) {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = progressShape.strokeEnd
animation.toValue = percent / 100.0
animation.duration = 2.5
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut);
let shortestSide = min(view.frame.size.width, view.frame.size.height) - 30
let strokeWidth: CGFloat = 40.0
let frame = CGRect(x: 0, y: 0, width: shortestSide - strokeWidth, height: shortestSide - strokeWidth)
backgroundShape.frame = frame
backgroundShape.position = view.center
backgroundShape.path = UIBezierPath(ovalIn: frame).cgPath
backgroundShape.strokeColor = UIColor.black.cgColor
backgroundShape.lineWidth = strokeWidth
backgroundShape.fillColor = UIColor.clear.cgColor
progressShape.frame = frame
progressShape.path = backgroundShape.path
progressShape.position = backgroundShape.position
progressShape.strokeColor = UIColor.red.cgColor
progressShape.lineWidth = backgroundShape.lineWidth
progressShape.fillColor = UIColor.clear.cgColor
progressShape.strokeEnd = CGFloat(percent/100.0)
if isAnimated {
progressShape.add(animation, forKey: nil)
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateIndicator(with: percent, isAnimated: true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment