Skip to content

Instantly share code, notes, and snippets.

@Wilsonilo
Created October 23, 2018 23:04
Show Gist options
  • Save Wilsonilo/c9384bcf1a5f1f733a55dcdb96121eb5 to your computer and use it in GitHub Desktop.
Save Wilsonilo/c9384bcf1a5f1f733a55dcdb96121eb5 to your computer and use it in GitHub Desktop.
Loader Animation With CAShapeLayer and CABasicAnimation
//
// LoaderUIView.swift
//
// Created by Wilson Munoz on 10/23/18.
// @yosoywil
// Based on documentation from:
// https://www.youtube.com/watch?v=O3ltwjDJaMk
// https://www.raywenderlich.com/449-how-to-implement-a-circular-image-loader-animation-with-cashapelayer
import UIKit
class LoaderUIView: UIView {
let circlePathLayer = CAShapeLayer()
let circleRadius: CGFloat = 20.0
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
func circleFrame() -> CGRect {
var circleFrame = CGRect(x: 0, y: 0, width: 2 * circleRadius, height: 2 * circleRadius)
let circlePathBounds = circlePathLayer.bounds
circleFrame.origin.x = circlePathBounds.midX - circleFrame.midX
circleFrame.origin.y = circlePathBounds.midY - circleFrame.midY
return circleFrame
}
func circlePath() -> UIBezierPath {
return UIBezierPath(ovalIn: circleFrame())
}
func configure(){
let center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
let circulalPath = UIBezierPath(arcCenter: center, radius: circleRadius,
startAngle: -.pi / 2,
endAngle: 2 * .pi, clockwise: true)
circlePathLayer.path = circulalPath.cgPath //You can also use circlePath().cgPath, but i couldn't find a way to change the startAngle without a new init.
circlePathLayer.frame = bounds
circlePathLayer.strokeColor = UIColor.midnightBlue()?.cgColor
circlePathLayer.lineWidth = 3
circlePathLayer.fillColor = UIColor.clear.cgColor
circlePathLayer.strokeEnd = 0
circlePathLayer.lineCap = kCALineCapRound
let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
basicAnimation.toValue = 1
basicAnimation.duration = 1.2
basicAnimation.fillMode = kCAFillModeForwards
basicAnimation.isRemovedOnCompletion = false
basicAnimation.repeatCount = .infinity
circlePathLayer.add(basicAnimation, forKey: "loadingBasicaAnimation")
self.layer.addSublayer(circlePathLayer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment