Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Last active June 17, 2018 11:02
Show Gist options
  • Select an option

  • Save lamprosg/634dfc27a518955547a2430167fbf503 to your computer and use it in GitHub Desktop.

Select an option

Save lamprosg/634dfc27a518955547a2430167fbf503 to your computer and use it in GitHub Desktop.
(iOS) CAShapeLayer circle
import UIKit
class CircleView: UIView {
var viewLoaded:Bool = false
var lineWidth:CGFloat = 10
var animationDuration:Double = 5
let circlePathLayer = CAShapeLayer()
private func animate() -> Void {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0
animation.toValue = 1
animation.duration = self.animationDuration
animation.autoreverses = false
animation.repeatCount = 1.0
self.circlePathLayer.add(animation, forKey: "line")
}
private func configure() {
let frame = circlePathFrame()
self.circlePathLayer.frame = frame
self.circlePathLayer.lineWidth = self.lineWidth
self.circlePathLayer.fillColor = UIColor.lightGray.cgColor
self.circlePathLayer.strokeColor = UIColor.blue.cgColor
//line shape (rounded corners)
self.circlePathLayer.lineCap = kCALineCapRound
self.circlePathLayer.path = UIBezierPath(ovalIn: frame).cgPath
layer.addSublayer(circlePathLayer)
backgroundColor = .green
}
private func circlePathFrame() -> CGRect {
let circleRadius = self.radius()
return CGRect(x:self.lineWidth/4, y: self.lineWidth/4, width: 2 * circleRadius , height: 2 * circleRadius)
}
private func radius() -> CGFloat {
if self.frame.size.width > self.frame.size.height {
return self.frame.size.height/2 - self.lineWidth/2
}
else {
return self.frame.size.width/2 - self.lineWidth/2
}
}
//MARK: - Layout subviews
override public func layoutSubviews() {
super.layoutSubviews()
if let _ = self.superview,
!self.viewLoaded {
self.viewLoaded = true
self.configure()
self.animate()
}
}
//MARK: - Reload circle
func reloadCircle() -> Void {
self.viewLoaded = false
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment