Stop animation at a certain point and start up from that point again - swift

Background
Hi all! I am creating a timer feature for my application.
Part of this timer includes a progress ring around the actual countdown numbers that fills as the timer progresses.
I added the image below in case my explanation was not easy to understand.
My goal is for the green stroke to stop animating when the "pause" button is tapped, and to continue animating when the "continue" button is tapped.
So far, the green stroke only animates correctly after pressing a start button.
To provide more background on how my code works, I added the content below.
To make the circle, I create a CAShapeLayer Object (shapeLayer) whose .path is equal to a circular UIBezierPath .CGPath
let center = view.center
let circularPath = UIBezierPath(arcCenter: center, radius: view.bounds.width/2.5, startAngle: -CGFloat.pi/2, endAngle: 2*CGFloat.pi, clockwise: true)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.systemGreen.cgColor
shapeLayer.lineCap = .round
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 7
shapeLayer.strokeEnd = 0
view.layer.addSublayer(shapeLayer)
Next, I animate the outside stroke using a CABasicAnimaton Object "basicAnimation". I do all my animation in the doAnimate() function detailed below.
func doAnimate(n: Int){
if n == 1{ //if n is 1, start from zero
basicAnimation.toValue = 0.80 // my circles start point is 0, and the endpoint at the top is .8 not 1
}//end of if
if n == 2{ //if n is 2, the timer was already started and the pause button has been pressed
//stop the animation where it is at
}//end of if
if n == 3{//if n is 3, the continue button has been pressed
// continue the animation from where it was stopped
}//end of if
basicAnimation.duration = CFTimeInterval(1500) //this is a set 25 minute timer which is why the duration is 1500
basicAnimation.fillMode = .forwards
basicAnimation.isRemovedOnCompletion = false
shapeLayer.add(basicAnimation, forKey: "urSoBasic")
}//end of func
Problem
In all of my IBOUtlet button functions, I call the doAnimate function with an integer n passed in.
The purpose of my integer 'n' is to decide where the stroke should be on the progress bar.
If n == 1, the stroke will start from 0.
If n == 2, that would mean the user has pressed the pause button, and I need the stroke to stop and hold where it is.
If n == 3, then the user pressed the continue button and I need the stroke to continue again.
I cannot get my animated stroke to pause when I press the pause button.
Similarly, I cannot get it to continue when I press the continue button.
I have been researching all day for code to fix this issue, and I cannot find any.
Question
I need the stroke to stop animating and stay where it is at after pressing the pause button.
I need the stroke to continue animating if the continue button is pressed.
How do I stop an animation and then make it pick back up from that point later?

You asked:
I need the stroke to stop animating and stay where it is at after pressing the pause button.
You can use presentation() to retrieve “a copy of the presentation layer object that represents the state of the layer as it currently appears onscreen”, i.e., the state of the layer mid-animation. Use that to set the strokeEnd before you remove the animation:
if let presentationLayer = progressShapeLayer.presentation() {
progressShapeLayer.strokeEnd = presentationLayer.strokeEnd
}
progressShapeLayer.removeAnimation(forKey: animationKey)
I need the stroke to continue animating if the continue button is pressed.
Use this strokeEnd value for your fromValue when you restart the animation.
For example:
#IBDesignable
public class CircularProgressView: UIView {
#IBInspectable var duration: CFTimeInterval = 10
#IBInspectable var lineWidth: CGFloat = 1 { didSet { updatePaths() } }
private(set) var isRunning = false
private var elapsed: CFTimeInterval = 0
private var startTime: CFTimeInterval!
private let animationKey = Bundle.main.bundleIdentifier! + ".strokeEnd"
private let backgroundShapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1).cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
return shapeLayer
}()
private let progressShapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = #colorLiteral(red: 0.2319213939, green: 0.5, blue: 0.224438305, alpha: 1).cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = .round
shapeLayer.strokeEnd = 0
return shapeLayer
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
public override func layoutSubviews() {
super.layoutSubviews()
updatePaths()
}
public override func prepareForInterfaceBuilder() {
progressShapeLayer.strokeEnd = 1 / 3
}
}
// MARK: - Public interface
public extension CircularProgressView {
func start(duration: CFTimeInterval) {
self.duration = duration
reset()
resume()
}
func pause() {
guard
isRunning,
let presentation = progressShapeLayer.presentation()
else {
return
}
elapsed += CACurrentMediaTime() - startTime
progressShapeLayer.strokeEnd = presentation.strokeEnd
progressShapeLayer.removeAnimation(forKey: animationKey)
}
func resume() {
guard !isRunning else { return }
isRunning = true
startTime = CACurrentMediaTime()
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = elapsed / duration
animation.toValue = 1
animation.duration = duration - elapsed
animation.delegate = self
progressShapeLayer.strokeEnd = 1
progressShapeLayer.add(animation, forKey: animationKey)
}
func reset() {
isRunning = false
progressShapeLayer.removeAnimation(forKey: animationKey)
progressShapeLayer.strokeEnd = 0
elapsed = 0
}
}
extension CircularProgressView: CAAnimationDelegate {
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
isRunning = false
}
}
// MARK: - Utility
private extension CircularProgressView {
func configure() {
layer.addSublayer(backgroundShapeLayer)
layer.addSublayer(progressShapeLayer)
}
func updatePaths() {
let radius = (min(bounds.width, bounds.height) - lineWidth) / 2
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: -.pi / 2, endAngle: 3 * .pi / 2, clockwise: true)
backgroundShapeLayer.lineWidth = lineWidth
progressShapeLayer.lineWidth = lineWidth
backgroundShapeLayer.path = path.cgPath
progressShapeLayer.path = path.cgPath
}
}
Yielding:

Related

Circle Progress Bar for Swift Count down

Inside the circle progress bar there is a constantly changing number (eg 250, 300, 1000). Whenever I click, the number will decrease and circle progress bar will move. I did it with the time counter. But I want to do it with my control. So when I click the button it will move, if I don't click it won't move.
My code :
import UIKit
class ViewController: UIViewController {
let shapeLAyer = CAShapeLayer()
let progressLayer = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
let center = view.center
let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi/2, endAngle: 2*CGFloat.pi, clockwise: true)
progressLayer.path = circularPath.cgPath
// ui edits
progressLayer.strokeColor = UIColor.black.cgColor
progressLayer.fillColor = UIColor.clear.cgColor
//progressLayer.fillColor = UIColor.clear.cgColor
progressLayer.lineCap = .round
progressLayer.lineWidth = 20.0
view.layer.addSublayer(progressLayer)
shapeLAyer.path = circularPath.cgPath
shapeLAyer.fillColor = UIColor.clear.cgColor
shapeLAyer.strokeColor = UIColor.red.cgColor
shapeLAyer.lineWidth = 10
shapeLAyer.lineCap = .round
shapeLAyer.strokeEnd = 0
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handle)))
view.layer.addSublayer(shapeLAyer)
}
#objc func handle(){
let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
basicAnimation.toValue = 1
basicAnimation.duration = 3
shapeLAyer.add(basicAnimation, forKey: "urSoBasic")
}
}
[![enter image description here][1]][1]
You can achieve this type of progress by setting proper from value, to value and with the mode of CABasicAnimation
Here, I take two var one for total number (for total progress) and one for current progress number.
From these two var, I converted this value to between 0-1.
First, in your code UIBezierPath angle is wrong.
Replace this line by
let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi/2, endAngle: 3*CGFloat.pi / 2, clockwise: true)
class ViewController: UIViewController {
// Other code
private let totalNumber: CGFloat = 300.0
private var currentProgressNumber: CGFloat = 0
private let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
// viewDidLoad code
func playAnimation(){
if currentProgressNumber > totalNumber || currentProgressNumber < 0 {
return
}
basicAnimation.fromValue = basicAnimation.toValue
basicAnimation.toValue = currentProgressNumber/totalNumber
basicAnimation.isRemovedOnCompletion = false
basicAnimation.duration = 3
basicAnimation.fillMode = CAMediaTimingFillMode.both
shapeLAyer.add(basicAnimation, forKey: "urSoBasic")
}
#IBAction func onIncrement(_ sender: UIButton) {
currentProgressNumber += 15 //<-- Change your increment interval here
playAnimation()
}
#IBAction func onDecrement(_ sender: UIButton) {
currentProgressNumber -= 15 //<-- Change your increment interval here
playAnimation()
}
}
Note: Replace your animation function with playAnimation() and also change the increment-decrement value as per your requirement for testing I used 15.

Change color gradient around donut view

I am trying to make an animated donut view that when given a value between 0 and 100 it will animate round the view up to that number. I have this working fine but want to fade the color from one to another, then another on the way around. Currently, when I add my gradient it goes from left to right and not around the circumference of the donut view.
class CircleScoreView: UIView {
private let outerCircleLayer = CAShapeLayer()
private let outerCircleGradientLayer = CAGradientLayer()
private let outerCircleLineWidth: CGFloat = 5
override init(frame: CGRect) {
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
buildLayers()
}
/// Value must be within 0...100 range
func setScore(_ value: Int, animated: Bool = false) {
if value != 0 {
let clampedValue: CGFloat = CGFloat(value.clamped(to: 0...100)) / 100
if !animated {
outerCircleLayer.strokeEnd = clampedValue
} else {
let outerCircleAnimation = CABasicAnimation(keyPath: "strokeEnd")
outerCircleAnimation.duration = 1.0
outerCircleAnimation.fromValue = 0
outerCircleAnimation.toValue = clampedValue
outerCircleAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
outerCircleLayer.strokeEnd = clampedValue
outerCircleLayer.add(outerCircleAnimation, forKey: "outerCircleAnimation")
}
outerCircleGradientLayer.colors = [Constant.Palette.CircleScoreView.startValue.cgColor,
Constant.Palette.CircleScoreView.middleValue.cgColor,
Constant.Palette.CircleScoreView.endValue.cgColor]
}
}
private func buildLayers() {
// Outer background circle
let arcCenter = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
let startAngle = CGFloat(-0.5 * Double.pi)
let endAngle = CGFloat(1.5 * Double.pi)
let circlePath = UIBezierPath(arcCenter: arcCenter,
radius: (frame.size.width - outerCircleLineWidth) / 2,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
// Outer circle
setupOuterCircle(outerCirclePath: circlePath)
}
private func setupOuterCircle(outerCirclePath: UIBezierPath) {
outerCircleLayer.path = outerCirclePath.cgPath
outerCircleLayer.fillColor = UIColor.clear.cgColor
outerCircleLayer.strokeColor = UIColor.black.cgColor
outerCircleLayer.lineWidth = outerCircleLineWidth
outerCircleLayer.lineCap = CAShapeLayerLineCap.round
outerCircleGradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
outerCircleGradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
outerCircleGradientLayer.frame = bounds
outerCircleGradientLayer.mask = outerCircleLayer
layer.addSublayer(outerCircleGradientLayer)
}
}
I am going for something like this but the color isn't one block but gradients around the donut view from one color to the next.
If you imported AngleGradientLayer into your project then all you should need to do is change:
private let outerCircleGradientLayer = CAGradientLayer() to
private let outerCircleGradientLayer = AngleGradientLayer()

Swift: how to invalidate timer on animated SKShapenode countdown?

Alright I'm building a sprite kit game and on one of my previous questions, I got the code that lets a circle skshapenode "unwind" in accordance with a timer that runs out (so that the circle has disappeared by the time the timer is done).
Here was my question: Swift, sprite kit game: Have circle disappear in clockwise manner? On timer?
And here is the code that I've been using:
func addCircle() {
circle = SKShapeNode(circleOfRadius: 50)
let circleColor = UIColor(red: 102/255, green: 204/255, blue: 255/255, alpha: 1)
circle.fillColor = circleColor
circle.strokeColor = SKColor.clearColor()
circle.position = CGPoint (x: self.frame.size.width * 0.5, y: self.frame.size.height * 0.5+45)
circle.zPosition = 200
circle.zRotation = CGFloat(M_PI_2)
addChild(circle)
countdown(circle, steps: 120, duration: 5) { //change steps to change how much of the circle it takes away at a time
//Performed when circle timer ends:
print("circle done")
self.gameSoundTrack.stop()
self.removeAllChildren()
self.removeAllActions()
self.viewController.removeSaveMe(self)
self.GOSceneNodes() //Implements GOScene
self.viewController.addGOScene(self) //Implements GOViewController
}
}
// Creates an animated countdown timer
func countdown(circle:SKShapeNode, steps:Int, duration:NSTimeInterval, completion:()->Void) {
let radius = CGPathGetBoundingBox(circle.path).width/2
let timeInterval = duration/NSTimeInterval(steps)
let incr = 1 / CGFloat(steps)
var percent = CGFloat(1.0)
let animate = SKAction.runBlock({
percent -= incr
circle.path = self.circle(radius, percent:percent)
})
let wait = SKAction.waitForDuration(timeInterval)
let action = SKAction.sequence([wait, animate])
runAction(SKAction.repeatAction(action,count:steps-1)) {
self.runAction(SKAction.waitForDuration(timeInterval)) {
circle.path = nil
completion()
}
}
}
// Creates a CGPath in the shape of a pie with slices missing
func circle(radius:CGFloat, percent:CGFloat) -> CGPath {
let start:CGFloat = 0
let end = CGFloat(M_PI*2) * percent
let center = CGPointZero
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(center)
bezierPath.addArcWithCenter(center, radius: radius, startAngle: start, endAngle: end, clockwise: true)
bezierPath.addLineToPoint(center)
return bezierPath.CGPath
}
This all works well, however I need a way to invalidate the countdown for the circle if another button within the game is pressed so that everything that is performed when the timer runs out (everything after //Performed when circle timer ends: above) is NOT performed.
I have tried
circle.removeAllActions()
circle.removeFromParent()
when the button is pressed, however this just removes the circle and everything is still executed even though the circle is gone.
I'm pretty new to Swift and I can't figure out what part of those 3 functions I need to invalidate or stop in order to stop the countdown from finishing. How can I accomplish this?
You can stop an action by adding a key to the action and then run
removeActionForKey("actionKey")
To add a key to the action, replace the countdown method with the following:
// Creates an animated countdown timer
func countdown(circle:SKShapeNode, steps:Int, duration:NSTimeInterval, completion:()->Void) {
let radius = CGPathGetBoundingBox(circle.path).width/2
let timeInterval = duration/NSTimeInterval(steps)
let incr = 1 / CGFloat(steps)
var percent = CGFloat(1.0)
let animate = SKAction.runBlock({
percent -= incr
circle.path = self.circle(radius, percent:percent)
})
let wait = SKAction.waitForDuration(timeInterval)
let action = SKAction.sequence([wait, animate])
let completed = SKAction.runBlock{
circle.path = nil
completion()
}
let countDown = SKAction.repeatAction(action,count:steps-1)
let sequence = SKAction.sequence([countDown, SKAction.waitForDuration(timeInterval),completed])
runAction(sequence, withKey: "actionKey")
}

CABasicAnimation ignores duration

I can't seem to control the duration of a simple Core Animation whether I use a CATransation or not.
The transaction completion code fires after my duration setting like I'd expect, but the rotation animation always takes about 0.5 seconds no matter what duration it's set to.
But if I comment out the last line that sets the transform, the animation moves at the proper speed, but then snaps back to the original rotation.
What am I missing?
class MyControl: NSControl {
var shapeLayer = CAShapeLayer()
required override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.wantsLayer = true
self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawPolicy.OnSetNeedsDisplay
// create a triangle shape
let path = NSBezierPath()
path.moveToPoint(CGPointMake(45.0, 25.0))
path.lineToPoint(CGPointMake(5.0, 5.0))
path.lineToPoint(CGPointMake(5.0, 45.0))
path.lineToPoint(CGPointMake(45.0, 25.0))
path.closePath()
shapeLayer.frame = self.bounds
shapeLayer.path = path.toCGPath()
shapeLayer.fillColor = NSColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0).CGColor
self.layer!.addSublayer(shapeLayer)
}
override func mouseUp(theEvent: NSEvent){
let duration = 2.0
let endAngle = -90.0
let startAngle = shapeLayer.valueForKey("transform.rotation")
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
CATransaction.setCompletionBlock({
Swift.print("this fires after 2 seconds")
})
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.removedOnCompletion = true
rotateAnimation.autoreverses = false
rotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
rotateAnimation.duration = duration
rotateAnimation.fromValue = startAngle
rotateAnimation.toValue = endAngle.degreesToRadians
shapeLayer.addAnimation(rotateAnimation, forKey: rotateAnimation.keyPath)
CATransaction.commit()
// mystery line...
shapeLayer.transform = CATransform3DMakeRotation(endAngle.degreesToRadians, 0.0, 0.0, 1.0)
}
}
On a side note, I made use of a couple of useful extensions... toCGPath in NSBezierPath and degreesToRadians for CGFloat.
The reason why you are seeing this strange behaviour is usage of explicit CATransaction begin--commit. This will in turn add a nested CATransaction within the one already owned by the run loop. So what happens is, your inner transaction gets committed, but before the associated animations finish, you have an immediate new value for the transform. This will cause this glitch where your layer will just quickly rotate and vanish.
Instead of this, the straight forward way to do is
1. Create your animation
2. Set a delegate for your animation
3. In delegate call back set the target value you would want the layer to remain in.
override func mouseUp(theEvent: NSEvent){
let duration = 2.0
let endAngle = -90.0
let startAngle = shapeLayer.valueForKey("transform.rotation")
//Set up animation
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.removedOnCompletion = true
rotateAnimation.autoreverses = false
rotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
rotateAnimation.duration = duration
rotateAnimation.fromValue = startAngle
rotateAnimation.toValue = endAngle * 3.142/180
//Setup delegate
rotateAnimation.delegate = self
shapeLayer.addAnimation(rotateAnimation, forKey: #"rotationAnimation")
}
public override func animationDidStop(anim: CAAnimation, finished flag: Bool){
shapeLayer.transform = CATransform3DMakeRotation(CGFloat(-90.0 * 3.142/180), 0.0, 0.0, 1.0)
}
P.S: I have not run this code, and also note sure what value you want to set for the transform of your layer once the animation completes.
I think the problem is because your startAngle and endAngle. Try to change it like this. This works for me
private let startAngle: CGFloat = CGFloat(-M_PI_2)
private let endAngle: CGFloat = CGFloat(-M_PI_2) + CGFloat(M_PI * 2)

Animate drawing of a circle

I'm looking for a way to animate the drawing of a circle. I have been able to create the circle, but it draws it all together.
Here is my CircleView class:
import UIKit
class CircleView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
// Get the Graphics Context
var context = UIGraphicsGetCurrentContext();
// Set the circle outerline-width
CGContextSetLineWidth(context, 5.0);
// Set the circle outerline-colour
UIColor.redColor().set()
// Create Circle
CGContextAddArc(context, (frame.size.width)/2, frame.size.height/2, (frame.size.width - 10)/2, 0.0, CGFloat(M_PI * 2.0), 1)
// Draw
CGContextStrokePath(context);
}
}
And here is how I add it to the view hierarchy in my view controller:
func addCircleView() {
let diceRoll = CGFloat(Int(arc4random_uniform(7))*50)
var circleWidth = CGFloat(200)
var circleHeight = circleWidth
// Create a new CircleView
var circleView = CircleView(frame: CGRectMake(diceRoll, 0, circleWidth, circleHeight))
view.addSubview(circleView)
}
Is there a way to animate the drawing of the circle over 1 second?
Example, part way through the animation it would look something like the blue line in this image:
The easiest way to do this is to use the power of core animation to do most of the work for you. To do that, we'll have to move your circle drawing code from your drawRect function to a CAShapeLayer. Then, we can use a CABasicAnimation to animate CAShapeLayer's strokeEnd property from 0.0 to 1.0. strokeEnd is a big part of the magic here; from the docs:
Combined with the strokeStart property, this property defines the
subregion of the path to stroke. The value in this property indicates
the relative point along the path at which to finish stroking while
the strokeStart property defines the starting point. A value of 0.0
represents the beginning of the path while a value of 1.0 represents
the end of the path. Values in between are interpreted linearly along
the path length.
If we set strokeEnd to 0.0, it won't draw anything. If we set it to 1.0, it'll draw a full circle. If we set it to 0.5, it'll draw a half circle. etc.
So, to start, lets create a CAShapeLayer in your CircleView's init function and add that layer to the view's sublayers (also be sure to remove the drawRect function since the layer will be drawing the circle now):
let circleLayer: CAShapeLayer!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
// Use UIBezierPath as an easy way to create the CGPath for the layer.
// The path should be the entire circle.
let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(Double.pi * 2.0), clockwise: true)
// Setup the CAShapeLayer with the path, colors, and line width
circleLayer = CAShapeLayer()
circleLayer.path = circlePath.CGPath
circleLayer.fillColor = UIColor.clearColor().CGColor
circleLayer.strokeColor = UIColor.redColor().CGColor
circleLayer.lineWidth = 5.0;
// Don't draw the circle initially
circleLayer.strokeEnd = 0.0
// Add the circleLayer to the view's layer's sublayers
layer.addSublayer(circleLayer)
}
Note: We're setting circleLayer.strokeEnd = 0.0 so that the circle isn't drawn right away.
Now, lets add a function that we can call to trigger the circle animation:
func animateCircle(duration: NSTimeInterval) {
// We want to animate the strokeEnd property of the circleLayer
let animation = CABasicAnimation(keyPath: #keyPath(CAShapeLayer.strokeEnd))
// Set the animation duration appropriately
animation.duration = duration
// Animate from 0 (no circle) to 1 (full circle)
animation.fromValue = 0
animation.toValue = 1
// Do a linear animation (i.e. the speed of the animation stays the same)
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
// Set the circleLayer's strokeEnd property to 1.0 now so that it's the
// right value when the animation ends.
circleLayer.strokeEnd = 1.0
// Do the actual animation
circleLayer.add(animation, forKey: "animateCircle")
}
Then, all we need to do is change your addCircleView function so that it triggers the animation when you add the CircleView to its superview:
func addCircleView() {
let diceRoll = CGFloat(Int(arc4random_uniform(7))*50)
var circleWidth = CGFloat(200)
var circleHeight = circleWidth
// Create a new CircleView
var circleView = CircleView(frame: CGRectMake(diceRoll, 0, circleWidth, circleHeight))
view.addSubview(circleView)
// Animate the drawing of the circle over the course of 1 second
circleView.animateCircle(1.0)
}
All that put together should look something like this:
Note: It won't repeat like that, it'll stay a full circle after it animates.
Mikes answer updated for Swift 3.0
var circleLayer: CAShapeLayer!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
// Use UIBezierPath as an easy way to create the CGPath for the layer.
// The path should be the entire circle.
let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
// Setup the CAShapeLayer with the path, colors, and line width
circleLayer = CAShapeLayer()
circleLayer.path = circlePath.cgPath
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.strokeColor = UIColor.red.cgColor
circleLayer.lineWidth = 5.0;
// Don't draw the circle initially
circleLayer.strokeEnd = 0.0
// Add the circleLayer to the view's layer's sublayers
layer.addSublayer(circleLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func animateCircle(duration: TimeInterval) {
// We want to animate the strokeEnd property of the circleLayer
let animation = CABasicAnimation(keyPath: "strokeEnd")
// Set the animation duration appropriately
animation.duration = duration
// Animate from 0 (no circle) to 1 (full circle)
animation.fromValue = 0
animation.toValue = 1
// Do a linear animation (i.e The speed of the animation stays the same)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
// Set the circleLayer's strokeEnd property to 1.0 now so that it's the
// Right value when the animation ends
circleLayer.strokeEnd = 1.0
// Do the actual animation
circleLayer.add(animation, forKey: "animateCircle")
}
To call the function:
func addCircleView() {
let diceRoll = CGFloat(Int(arc4random_uniform(7))*50)
var circleWidth = CGFloat(200)
var circleHeight = circleWidth
// Create a new CircleView
let circleView = CircleView(frame: CGRect(x: diceRoll, y: 0, width: circleWidth, height: circleHeight))
//let test = CircleView(frame: CGRect(x: diceRoll, y: 0, width: circleWidth, height: circleHeight))
view.addSubview(circleView)
// Animate the drawing of the circle over the course of 1 second
circleView.animateCircle(duration: 1.0)
}
Mike's answer is great! Another nice and simple way to do it is use drawRect combined with setNeedsDisplay(). It seems laggy, but its not :-)
We want to draw a circle starting from the top, which is -90° and ends at 270°. The circle's center is (centerX, centerY), with a given radius. CurrentAngle is the current angle of the end-point of the circle, going from minAngle (-90) to maxAngle (270).
// MARK: Properties
let centerX:CGFloat = 55
let centerY:CGFloat = 55
let radius:CGFloat = 50
var currentAngle:Float = -90
let minAngle:Float = -90
let maxAngle:Float = 270
In drawRect, we specify how the circle is supposed to display :
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let path = CGPathCreateMutable()
CGPathAddArc(path, nil, centerX, centerY, radius, CGFloat(GLKMathDegreesToRadians(minAngle)), CGFloat(GLKMathDegreesToRadians(currentAngle)), false)
CGContextAddPath(context, path)
CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor)
CGContextSetLineWidth(context, 3)
CGContextStrokePath(context)
}
The problem is that right now, as currentAngle is not changing, the circle is static, and doesn't even show, as currentAngle = minAngle.
We then create a timer, and whenever that timer fires, we increase currentAngle. At the top of your class, add the timing between two fires :
let timeBetweenDraw:CFTimeInterval = 0.01
In your init, add the timer :
NSTimer.scheduledTimerWithTimeInterval(timeBetweenDraw, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
We can add the function that will be called when the timer fires :
func updateTimer() {
if currentAngle < maxAngle {
currentAngle += 1
}
}
Sadly, when running the app, nothing displays because we did not specify the system that it should draw again. This is done by calling setNeedsDisplay(). Here is the updated timer function :
func updateTimer() {
if currentAngle < maxAngle {
currentAngle += 1
setNeedsDisplay()
}
}
_
_
_
All the code you need is summed-up here :
import UIKit
import GLKit
class CircleClosing: UIView {
// MARK: Properties
let centerX:CGFloat = 55
let centerY:CGFloat = 55
let radius:CGFloat = 50
var currentAngle:Float = -90
let timeBetweenDraw:CFTimeInterval = 0.01
// MARK: Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
self.backgroundColor = UIColor.clearColor()
NSTimer.scheduledTimerWithTimeInterval(timeBetweenDraw, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
// MARK: Drawing
func updateTimer() {
if currentAngle < 270 {
currentAngle += 1
setNeedsDisplay()
}
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let path = CGPathCreateMutable()
CGPathAddArc(path, nil, centerX, centerY, radius, -CGFloat(M_PI/2), CGFloat(GLKMathDegreesToRadians(currentAngle)), false)
CGContextAddPath(context, path)
CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor)
CGContextSetLineWidth(context, 3)
CGContextStrokePath(context)
}
}
If you want to change the speed, just modify the updateTimer function, or the rate at which this function is called. Also, you might want to invalidate the timer once the circle is complete, which I forgot to do :-)
NB: To add the circle in your storyboard, just add a view, select it, go to its Identity Inspector, and as Class, specify CircleClosing.
Cheers! bRo
If you want a completion handler, this is another solution similar to the one by Mike S, done in Swift 3.0
func animateCircleFull(duration: TimeInterval) {
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = duration
animation.fromValue = 0
animation.toValue = 1
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
circleLayer.strokeEnd = 1.0
CATransaction.setCompletionBlock {
print("animation complete")
}
// Do the actual animation
circleLayer.add(animation, forKey: "animateCircle")
CATransaction.commit()
}
With the completion handler, you can run the animation again either by recursively calling the same function to do the animation over again (which won't look very nice), or you can have a reversed function that will continuously chain until a condition is met, for example:
func animate(duration: TimeInterval){
self.isAnimating = true
self.animateCircleFull(duration: 1)
}
func endAnimate(){
self.isAnimating = false
}
func animateCircleFull(duration: TimeInterval) {
if self.isAnimating{
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = duration
animation.fromValue = 0
animation.toValue = 1
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
circleLayer.strokeEnd = 1.0
CATransaction.setCompletionBlock {
self.animateCircleEmpty(duration: duration)
}
// Do the actual animation
circleLayer.add(animation, forKey: "animateCircle")
CATransaction.commit()
}
}
func animateCircleEmpty(duration: TimeInterval){
if self.isAnimating{
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = duration
animation.fromValue = 1
animation.toValue = 0
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
circleLayer.strokeEnd = 0
CATransaction.setCompletionBlock {
self.animateCircleFull(duration: duration)
}
// Do the actual animation
circleLayer.add(animation, forKey: "animateCircle")
CATransaction.commit()
}
}
To make it even fancier, you can change the direction of the animation like this:
func setCircleClockwise(){
let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
self.circleLayer.removeFromSuperlayer()
self.circleLayer = formatCirle(circlePath: circlePath)
self.layer.addSublayer(self.circleLayer)
}
func setCircleCounterClockwise(){
let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: false)
self.circleLayer.removeFromSuperlayer()
self.circleLayer = formatCirle(circlePath: circlePath)
self.layer.addSublayer(self.circleLayer)
}
func formatCirle(circlePath: UIBezierPath) -> CAShapeLayer{
let circleShape = CAShapeLayer()
circleShape.path = circlePath.cgPath
circleShape.fillColor = UIColor.clear.cgColor
circleShape.strokeColor = UIColor.red.cgColor
circleShape.lineWidth = 10.0;
circleShape.strokeEnd = 0.0
return circleShape
}
func animate(duration: TimeInterval){
self.isAnimating = true
self.animateCircleFull(duration: 1)
}
func endAnimate(){
self.isAnimating = false
}
func animateCircleFull(duration: TimeInterval) {
if self.isAnimating{
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = duration
animation.fromValue = 0
animation.toValue = 1
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
circleLayer.strokeEnd = 1.0
CATransaction.setCompletionBlock {
self.setCircleCounterClockwise()
self.animateCircleEmpty(duration: duration)
}
// Do the actual animation
circleLayer.add(animation, forKey: "animateCircle")
CATransaction.commit()
}
}
func animateCircleEmpty(duration: TimeInterval){
if self.isAnimating{
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = duration
animation.fromValue = 1
animation.toValue = 0
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
circleLayer.strokeEnd = 0
CATransaction.setCompletionBlock {
self.setCircleClockwise()
self.animateCircleFull(duration: duration)
}
// Do the actual animation
circleLayer.add(animation, forKey: "animateCircle")
CATransaction.commit()
}
}
updating #Mike S's answer for Swift 5
works for frame manually、 storyboard setup、 autolayout setup
class CircleView: UIView {
let circleLayer: CAShapeLayer = {
// Setup the CAShapeLayer with the path, colors, and line width
let circle = CAShapeLayer()
circle.fillColor = UIColor.clear.cgColor
circle.strokeColor = UIColor.red.cgColor
circle.lineWidth = 5.0
// Don't draw the circle initially
circle.strokeEnd = 0.0
return circle
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
func setup(){
backgroundColor = UIColor.clear
// Add the circleLayer to the view's layer's sublayers
layer.addSublayer(circleLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
// Use UIBezierPath as an easy way to create the CGPath for the layer.
// The path should be the entire circle.
let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(Double.pi * 2.0), clockwise: true)
circleLayer.path = circlePath.cgPath
}
func animateCircle(duration t: TimeInterval) {
// We want to animate the strokeEnd property of the circleLayer
let animation = CABasicAnimation(keyPath: "strokeEnd")
// Set the animation duration appropriately
animation.duration = t
// Animate from 0 (no circle) to 1 (full circle)
animation.fromValue = 0
animation.toValue = 1
// Do a linear animation (i.e. the speed of the animation stays the same)
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
// Set the circleLayer's strokeEnd property to 1.0 now so that it's the
// right value when the animation ends.
circleLayer.strokeEnd = 1.0
// Do the actual animation
circleLayer.add(animation, forKey: "animateCircle")
}
}
Usage :
sample code for frame manually、 storyboard setup、 autolayout setup
class ViewController: UIViewController {
#IBOutlet weak var circleV: CircleView!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func animateFrame(_ sender: UIButton) {
let diceRoll = CGFloat(Int(arc4random_uniform(7))*30)
let circleEdge = CGFloat(200)
// Create a new CircleView
let circleView = CircleView(frame: CGRect(x: 50, y: diceRoll, width: circleEdge, height: circleEdge))
view.addSubview(circleView)
// Animate the drawing of the circle over the course of 1 second
circleView.animateCircle(duration: 1.0)
}
#IBAction func animateAutolayout(_ sender: UIButton) {
let circleView = CircleView(frame: CGRect.zero)
circleView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(circleView)
circleView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
circleView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
circleView.widthAnchor.constraint(equalToConstant: 250).isActive = true
circleView.heightAnchor.constraint(equalToConstant: 250).isActive = true
// Animate the drawing of the circle over the course of 1 second
circleView.animateCircle(duration: 1.0)
}
#IBAction func animateStoryboard(_ sender: UIButton) {
// Animate the drawing of the circle over the course of 1 second
circleV.animateCircle(duration: 1.0)
}
}
No only you can subclass an UIView, you can also go slightly deeper, subclass an CALayer
In other words, CoreAnimation's strokeEnd is OK. To call CALayer's draw(in ctx:) frequently is also OK
and the round line cap is nice
The key point is to override CALayer's method action(forKey:)
Actions define dynamic behaviors for a layer. For example, the animatable properties of a layer typically have corresponding action objects to initiate the actual animations. When that property changes, the layer looks for the action object associated with the property name and executes it.
The internal subclass for CAShapeLayer
/**
The internal subclass for CAShapeLayer.
This is the class that handles all the drawing and animation.
This class is not interacted with, instead
properties are set in UICircularRing
*/
class UICircularRingLayer: CAShapeLayer {
// MARK: Properties
#NSManaged var val: CGFloat
let ringWidth: CGFloat = 20
let startAngle = CGFloat(-90).rads
// MARK: Init
override init() {
super.init()
}
override init(layer: Any) {
guard let layer = layer as? UICircularRingLayer else { fatalError("unable to copy layer") }
super.init(layer: layer)
}
required init?(coder aDecoder: NSCoder) { return nil }
// MARK: Draw
/**
Override for custom drawing.
Draws the ring
*/
override func draw(in ctx: CGContext) {
super.draw(in: ctx)
UIGraphicsPushContext(ctx)
// Draw the rings
drawRing(in: ctx)
UIGraphicsPopContext()
}
// MARK: Animation methods
/**
Watches for changes in the val property, and setNeedsDisplay accordingly
*/
override class func needsDisplay(forKey key: String) -> Bool {
if key == "val" {
return true
} else {
return super.needsDisplay(forKey: key)
}
}
/**
Creates animation when val property is changed
*/
override func action(forKey event: String) -> CAAction? {
if event == "val"{
let animation = CABasicAnimation(keyPath: "val")
animation.fromValue = presentation()?.value(forKey: "val")
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.duration = 2
return animation
} else {
return super.action(forKey: event)
}
}
/**
Draws the ring for the view.
Sets path properties according to how the user has decided to customize the view.
*/
private func drawRing(in ctx: CGContext) {
let center: CGPoint = CGPoint(x: bounds.midX, y: bounds.midY)
let radiusIn: CGFloat = (min(bounds.width, bounds.height) - ringWidth)/2
// Start drawing
let innerPath: UIBezierPath = UIBezierPath(arcCenter: center,
radius: radiusIn,
startAngle: startAngle,
endAngle: toEndAngle,
clockwise: true)
// Draw path
ctx.setLineWidth(ringWidth)
ctx.setLineJoin(.round)
ctx.setLineCap(CGLineCap.round)
ctx.setStrokeColor(UIColor.red.cgColor)
ctx.addPath(innerPath.cgPath)
ctx.drawPath(using: .stroke)
}
var toEndAngle: CGFloat {
return (val * 360.0).rads + startAngle
}
}
helper methods
/**
A private extension to CGFloat in order to provide simple
conversion from degrees to radians, used when drawing the rings.
*/
extension CGFloat {
var rads: CGFloat { return self * CGFloat.pi / 180 }
}
use an UIView subclass, with the internal custom CALayer
#IBDesignable open class UICircularRing: UIView {
/**
Set the ring layer to the default layer, casted as custom layer
*/
var ringLayer: UICircularRingLayer {
return layer as! UICircularRingLayer
}
/**
Overrides the default layer with the custom UICircularRingLayer class
*/
override open class var layerClass: AnyClass {
return UICircularRingLayer.self
}
/**
Override public init to setup() the layer and view
*/
override public init(frame: CGRect) {
super.init(frame: frame)
// Call the internal initializer
setup()
}
/**
Override public init to setup() the layer and view
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Call the internal initializer
setup()
}
/**
This method initializes the custom CALayer to the default values
*/
func setup(){
// Helps with pixelation and blurriness on retina devices
ringLayer.contentsScale = UIScreen.main.scale
ringLayer.shouldRasterize = true
ringLayer.rasterizationScale = UIScreen.main.scale * 2
ringLayer.masksToBounds = false
backgroundColor = UIColor.clear
ringLayer.backgroundColor = UIColor.clear.cgColor
ringLayer.val = 0
}
func startAnimation() {
ringLayer.val = 1
}
}
Usage:
class ViewController: UIViewController {
let progressRing = UICircularRing(frame: CGRect(x: 100, y: 100, width: 250, height: 250))
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(progressRing)
}
#IBAction func animate(_ sender: UIButton) {
progressRing.startAnimation()
}
}
with an indicator image to set up the angle