Start/stop image view rotation animations - ios

I have a start/stop button and an image view which I want to rotate.
When I press the button I want the to start rotating and when I press the button again the image should stop rotating. I am currently using an UIView animation, but I haven't figured out a way to stop the view animations.
I want the image to rotate, but when the animation stops the image shouldn't go back to the starting position, but instead continue the animation.
var isTapped = true
#IBAction func startStopButtonTapped(_ sender: Any) {
ruotate()
isTapped = !isTapped
}
func ruotate() {
if isTapped {
UIView.animate(withDuration: 5, delay: 0, options: .repeat, animations: { () -> Void in
self.imageWood.transform = self.imageWood.transform.rotated(by: CGFloat(M_PI_2))
}, completion: { finished in
ruotate()
})
} }
It is my code, but it doesn't work like I aspect.

Swift 3.x
Start Animation
let rotationAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: .pi * 2.0)
rotationAnimation.duration = 0.5;
rotationAnimation.isCumulative = true;
rotationAnimation.repeatCount = .infinity;
self.imageWood?.layer.add(rotationAnimation, forKey: "rotationAnimation")
Stop animation
self.imageWood?.layer.removeAnimation(forKey: "rotationAnimation")
Swift 2.x
Start Animation
let rotationAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(double: M_PI * 2.0)
rotationAnimation.duration = 1;
rotationAnimation.cumulative = true;
rotationAnimation.repeatCount = .infinity;
self.imageWood?.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation")
Stop animation
self.imageWood?.layer.removeAnimation(forKey: "rotationAnimation")

If you use UIView Animation the OS still creates one or more CAAnimation objects. Thus, to stop a UIView animation you can still use:
myView.layer.removeAllAnimations()
Or if you create the animation using a CAAnimation on a layer:
myLayer.removeAllAnimations()
In either case, you can capture the current state of the animation and set that as the final state before removing the animation. If you're doing an animation on a view's transform, like in this question, that code might look like this:
func stopAnimationForView(_ myView: UIView) {
//Get the current transform from the layer's presentation layer
//(The presentation layer has the state of the "in flight" animation)
let transform = myView.layer.presentationLayer.transform
//Set the layer's transform to the current state of the transform
//from the "in-flight" animation
myView.layer.transform = transform
//Now remove the animation
//and the view's layer will keep the current rotation
myView.layer.removeAllAnimations()
}
If you're animating a property other than the transform you'd need to change the code above.

using your existing code you can achieve it the following way
var isTapped = true
#IBAction func startStopButtonTapped(_ sender: Any) {
ruotate()
isTapped = !isTapped
}
func ruotate() {
if isTapped {
let rotationAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: Double.pi * 2.0)
rotationAnimation.duration = 1;
rotationAnimation.isCumulative = true;
rotationAnimation.repeatCount = HUGE;
self.imageWood?.layer.add(rotationAnimation, forKey: "rotationAnimation")
}else{
self.imageWood?.layer.removeAnimation(forKey: "rotationAnimation")
}
}

Apple added a new class, UIViewPropertyAnimator, to iOS 10. A UIViewPropertyAnimator allows you to easily create UIView-based animations that can be paused, reversed, and scrubbed back and forth.
If you refactor your code to use a A UIViewPropertyAnimator you should be able to pause and resume your animation.
I have a sample project on Github that demonstrates using a UIViewPropertyAnimator. I suggest taking a look at that.

Your code make the image rotate for 2PI angle, but if you click on the button while the rotation is not ended, the animation will finish before stop, that's why it comes to the initial position.
You should use CABasicAnimation to use a rotation that you can stop at anytime keeping the last position.

Related

UIView animation snaps back to original state before transitioning to a new view

I have some UIButtons that I'm animating indefinitely. The buttons all have 3 sublayers that are added, each of which have their own animation. I'm initializing these animations on viewDidAppear which works great - they fade in and start rotating. The problem is that when I transition to a new view, the animations seem to "snap" back to their initial state, then back to some other state right before the transition occurs. I've tried explicitly removing all of the animations on viewWillDisappear, even tried hiding the entire UIButton itself, but nothing seems to prevent this weird snapping behavior from occurring.
Here's a gif of what's happening (this is me transitioning back and forth between two views):
func animateRotation() {
// Gets called on viewDidAppear
let rotationRight: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationRight.toValue = Double.pi * 2
rotationRight.duration = 4
rotationRight.isCumulative = true
rotationRight.repeatCount = Float.greatestFiniteMagnitude
rotationRight.isRemovedOnCompletion = false
rotationRight.fillMode = .forwards
let rotationLeft: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationLeft.toValue = Double.pi * -2
rotationLeft.duration = 3
rotationLeft.isCumulative = true
rotationLeft.repeatCount = Float.greatestFiniteMagnitude
rotationLeft.isRemovedOnCompletion = false
rotationLeft.fillMode = .forwards
let circleImage1 = UIImage(named: "circle_1")?.cgImage
circleLayer1.frame = self.bounds
circleLayer1.contents = circleImage1
circleLayer1.add(rotationRight, forKey: "rotationAnimation")
layer.addSublayer(circleLayer1)
let circleImage2 = UIImage(named: "circle_2")?.cgImage
circleLayer2.frame = self.bounds
circleLayer2.contents = circleImage2
circleLayer2.add(rotationLeft, forKey: "rotationAnimation")
layer.addSublayer(circleLayer2)
let circleImage3 = UIImage(named: "circle_3")?.cgImage
circleLayer3.frame = self.bounds
circleLayer3.contents = circleImage3
circleLayer3.add(rotationRight, forKey: "rotationAnimation")
layer.addSublayer(circleLayer3)
}
I would think something as simple as this would hide the button completely as soon as it knows it's going away:
override func viewWillDisappear(_ animated: Bool) {
animatedButton.isHidden = true
}
What's also interesting is that this seems to stop happening if I let it run for a couple minutes. This tells me that it might be some sort of race condition. Just not sure what that race might be...
When you use the UIView set of animations they set the actual state to the final state and then start the animation, ie:
UIView.animate(withDuration: 1) { view.alpha = 0 }
If you check alpha right after the animation starts, it's already 0.
This is a convenience that UIView does for you but that CALayer does not. When you set a CALayer animation you are only setting the animation value, not the actual value of the variable, so when the animation is done, the layer snaps back to its original value. Check the layer value while you are in the middle of the animation and you will see the real value has not changed; only the animated value in the presentation layer has changed.
If you want to replicate the UIView behavior you need to either set the actual final value not he layer when the animation begins or in the use the delegate to set it when the animation ends.

CALayer Rotation animation is not working on presented ViewController

I have two view controllers (i.e firstVC and secondVC). I am presenting secondVC over firstVC and trying to achieve rotation animation but it's not working, I have tried running animation on the main thread with some delay but it's giving weird behavior. Following is the code I am using to rotate the view.
extension UIView {
private static let kRotationAnimationKey = "rotationanimationkey"
func rotate(duration: Double = 1, delay: Int = 0) {
if layer.animation(forKey: UIView.kRotationAnimationKey) == nil {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = Float.pi * 2.0
rotationAnimation.duration = duration
rotationAnimation.repeatCount = Float.infinity
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(delay)) {
self.layer.add(rotationAnimation, forKey: UIView.kRotationAnimationKey)
}
}
}
func stopRotating() {
if layer.animation(forKey: UIView.kRotationAnimationKey) != nil {
layer.removeAnimation(forKey: UIView.kRotationAnimationKey)
}
}}
Note: By pushing 'secondVC' animation is working properly. But I wanted to present 'secondVC'.
I am not getting what's happening during the presentation of the view controller and rotation animation.
Please let me know if you find any solution.
For using custom presentation transition you have to confirm to UIViewControllerTransitioningDelegate. UIKit always call animationController(forPresented:presenting:source:) to see if a UIViewControllerAnimatedTransitioning is returned. If it is returning nil then default animation is used.

How would I lower the speed of the rotation to 0 in Swift?

I have this code that rotates my imageview but when I press my pause button I want the rotation speed to be 0. How would I do that?
#IBAction func playButtonL(sender: AnyObject) {
rotation.toValue = NSNumber(double: M_PI * 2)
rotation.duration = 2
rotation.cumulative = true
rotation.repeatCount = FLT_MAX
self.leftCircleImageView.layer.addAnimation(rotation, forKey: "rotationAnimation")
}
#IBAction func pauseButtonR(sender: AnyObject) {
}
To Reduce time of animation you can use
rotation.duration = 2
To stop reset it's state default you can use
cabasicanimation.removedOnCompletion = NO;
cabasicanimation.fillMode = kCAFillModeForwards;
Answer credits and reference :
CABasicAnimation resets to initial value after animation completes
Hope it helps! let me know if you need any further help.

'Press and hold' animation without NSTimer

Update: The NSTimer approach works now, but comes with a huge performance hit. The question is now narrowed down to an approach without NSTimers.
I'm trying to animate a 'Press and hold' interactive animation. After following a load of SO answers, I've mostly followed the approach in Controlling Animation Timing by #david-rönnqvist. And it works, if I use a Slider to pass the layer.timeOffset.
However, I can't seem to find a good way to continuously update the same animation on a press and hold gesture. The animation either doesn't start, only shows the beginning frame or at some points finishes and refuses to start again.
Can anyone help with achieving the following effect, without the horrible NSTimer approach I'm currently experimenting with?
On user press, animation starts, circle fills up.
While user holds (not necessarily moving the finger), the animation should continue until the end and stay on that frame.
When user lifts finger, the animation should reverse, so the circle is empties again.
If the user lifts his finger during the animation or presses down again during the reverse, the animation should respond accordingly and either fill or empty from the current frame.
Here's a Github repo with my current efforts.
As mentioned, the following code works well. It's triggered by a slider and does its job great.
func animationTimeOffsetToPercentage(percentage: Double) {
if fillShapeLayer == nil {
fillShapeLayer = constructFillShapeLayer()
}
guard let fillAnimationLayer = fillShapeLayer, let _ = fillAnimationLayer.animationForKey("animation") else {
print("Animation not found")
return
}
let timeOffset = maximumDuration * percentage
print("Set animation to percentage \(percentage) with timeOffset: \(timeOffset)")
fillAnimationLayer.timeOffset = timeOffset
}
However, the following approach with NSTimers works, but has an incredible performance hit. I'm looking for an approach which doesn't use the NSTimer.
func beginAnimation() {
if fillShapeLayer == nil {
fillShapeLayer = constructFillShapeLayer()
}
animationTimer?.invalidate()
animationTimer = NSTimer.schedule(interval: 0.1, repeats: true, block: { [unowned self] () -> Void in
if self.layer.timeOffset >= 1.0 {
self.layer.timeOffset = self.maximumDuration
}
else {
self.layer.timeOffset += 0.1
}
})
}
func reverseAnimation() {
guard let fillAnimationLayer = fillShapeLayer, let _ = fillAnimationLayer.animationForKey("animation") else {
print("Animation not found")
return
}
animationTimer?.invalidate()
animationTimer = NSTimer.schedule(interval: 0.1, repeats: true, block: { [unowned self] () -> Void in
if self.layer.timeOffset <= 0.0 {
self.layer.timeOffset = 0.0
}
else {
self.layer.timeOffset -= 0.1
}
})
}
When you use slider you use fillAnimationLayer layer for animation
fillAnimationLayer.timeOffset = timeOffset
However, in beginAnimation and reverseAnimation functions you are using self.layer.
Try to replace self.layer.timeOffset with self.fillShapeLayer!.timeOffset in your timer blocks.
The solution is two-fold;
Make sure the animation doesn't remove itself on completion and keeps its final frame. Easily accomplished with the following lines of code;
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
The hard part; you have to remove the original animation and start a new, fresh reverse animation that begins at the correct point. Doing this, gives me the following code;
func setAnimation(layer: CAShapeLayer, startPath: AnyObject, endPath: AnyObject, duration: Double)
{
// Always create a new animation.
let animation: CABasicAnimation = CABasicAnimation(keyPath: "path")
if let currentAnimation = layer.animationForKey("animation") as? CABasicAnimation {
// If an animation exists, reverse it.
animation.fromValue = currentAnimation.toValue
animation.toValue = currentAnimation.fromValue
let pauseTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
// For the timeSinceStart, we take the minimum from the duration or the time passed.
// If not, holding the animation longer than its duration would cause a delay in the reverse animation.
let timeSinceStart = min(pauseTime - startTime, currentAnimation.duration)
// Now convert for the reverse animation.
let reversePauseTime = currentAnimation.duration - timeSinceStart
animation.beginTime = pauseTime - reversePauseTime
// Remove the old animation
layer.removeAnimationForKey("animation")
// Reset startTime, to be when the reverse WOULD HAVE started.
startTime = animation.beginTime
}
else {
// This happens when there is no current animation happening.
startTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
animation.fromValue = startPath
animation.toValue = endPath
}
animation.duration = duration
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
layer.addAnimation(animation, forKey: "animation")
}
This Apple article explains how to do a proper pause and resume animation, which is converted to use with the reverse animation.

CABasicAnimation Quickly Jumping Before Animation Start

I have a CABasicAnimation animating the strokeEnd property of a CAShapeLayer. Every time I add the animation, it quickly jumps through the animation and then goes and does the real animation (as seen in the image above). If I add the animation in the viewDidLoad, this doesn't happen.
Here's my animation code:
let progressAnim = CABasicAnimation(keyPath: "strokeEnd")
progressAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
progressAnim.duration = 4.5
progressAnim.fromValue = 0.0
progressAnim.toValue = 1.0
progressAnim.removedOnCompletion = false
progressLayer.addAnimation(progressAnim, forKey: "progressAnimation")
progressLayer.strokeEnd = 1.0
I'm not sure what exactly I'm doing wrong, any help would be highly appreciated. Thanks!
My problem was with the line progressLayer.strokeEnd = 1.0. The reason I had that in my code was to stop the animation from going back to it's original values when it finished animating.
The next solution would be to set the fillMode to progressAnim.fillMode = kCAFillModeForwards and removedOnCompletion to progressAnim.removedOnCompletion = false. This sort of fixed my problem. But it created another. In my code, this solution doesn't update the strokeEnd property to the toValue.
My final solution was to set the toValue to the strokeEnd inside override func animationDidStop(anim: CAAnimation, finished flag: Bool).
My animation code:
let progressAnim = CABasicAnimation(keyPath: "strokeEnd")
progressAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
progressAnim.duration = animationDuration
progressAnim.fromValue = 0.0
progressAnim.toValue = 0.5
progressAnim.delegate = self
progressLayer.addAnimation(progressAnim, forKey: "progressAnimation")
Code for when animation is complete:
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
progressLayer.strokeEnd = 0.5
progressLayer.removeAllAnimations()
}

Resources