SpringWithDamping for CALayer animations? - ios

After playing around a lot with the UIView dynamic animations introduced in iOS 7, most notably:
[UIView animateWithDuration: delay: usingSpringWithDamping: initialSpringVelocity: options: animations: completion:];
I was wondering if there is an equivalent to 'SpringWithDamping/Velocity' method that can be accessed directly when creating a CALayer animation? I.e. either through CATransaction, CABasicAnimation or otherwise...
Thanks

in iOS9 Apple finally made the CASpringAnimation class public.
You can use it like that:
let spring = CASpringAnimation(keyPath: "position.x")
spring.damping = 5
spring.fromValue = myLayer.position.x
spring.toValue = myLayer.position.x + 100.0
spring.duration = spring.settlingDuration
myLayer.addAnimation(spring, forKey: nil)
Notice that you cannot set the animation duration - you need to ask the CASpringAnimation class for the settlingDuration (e.g. "How much time is going to take for the spring system to settle down") and then set it as the duration of your animation.
Check the header files for CASpringAnimation - it exposes a number of spring system variables you can adjust - stiffness, mass, etc.

There is (and have been for a while) a private class called CASpringAnimation that I'm pretty sure is being used behind it all (but I haven't verified it). Unfortunately, it is still private.

As David said, CASpringAnimation is private (for now?), but I recently came across RBBSpringAnimation from the RBBAnimation project.
I can definitely recommend this, it was very easy to drop in as a replacement for my existing CABasicAnimation.

I wrote a class to create CASpringAnimation instance. It works in a pretty simple way:
By creating a spring animation from UIKit API, it arrests the created CASpringAnimation instance from the view's layer, copies it and returns it.
But I don't know if it is App Store safe that to create CASpringAnimation in this way.
import UIKit
private let SharedCASpringAnimationFactory = CASpringAnimationFactory()
public class CASpringAnimationFactory {
private var dummyView: UIView
private init() {
dummyView = UIView(frame: CGRect.zeroRect)
}
private class var shared: CASpringAnimationFactory {
return SharedCASpringAnimationFactory
}
public class func animation(#keyPath: String, dumping: CGFloat, initialSpringVelocity: CGFloat) -> CABasicAnimation {
let duration = CATransaction.animationDuration()
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: dumping, initialSpringVelocity: initialSpringVelocity, options: nil,
animations: { () -> Void in
CASpringAnimationFactory.shared.dummyView.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: 100, height: 100))
}, completion: nil)
let dummyLayer = CASpringAnimationFactory.shared.dummyView.layer
let animations = dummyLayer.animationKeys().map {dummyLayer.animationForKey($0 as String) as CAAnimation}
let arrestedAnimation = animations.first!.copy() as CABasicAnimation
arrestedAnimation.keyPath = keyPath
arrestedAnimation.fromValue = nil
arrestedAnimation.toValue = nil
dummyLayer.removeAllAnimations()
shared.dummyView.bounds = CGRect.zeroRect
return arrestedAnimation
}
}

Related

UIViewPropertyAnimator repeat

I've taken a look at the answers in the following StackOverflow question but none seem to work for me: on the execution of the completion block, instead of performing the animation again, the program spews out "complete" ad infinitum without animating the view at all.
How can I repeat animation (using UIViewPropertyAnimator) certain number of times?
This is my AnimatorFactory class:
class AnimatorFactory {
#discardableResult
static func rotateRepeat(view: UIView) -> UIViewPropertyAnimator {
let rotate = UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 1.0, delay: 0.0, options: [.curveLinear], animations: {
view.transform = CGAffineTransform(rotationAngle: .pi)
}, completion: { _ in
print("complete")
self.rotateRepeat(view: view)
})
return rotate
}
}
It is called as you'd expect with AnimatorFactory.rotateRepeat(view: <someView>)
However, the problem as mentioned above occurs. What I'd expect is that the view would rotate repeatedly until some time that I decide to change or stop it; this is exactly the reason that I have chosen to use UIViewPropertyAnimator instead of UIView.animate(withDuration:animations).
What's the best way then to create interactive, repeatable UIView animations? Much appreciated.
Your code is working fine. The trouble is that your animation does nothing after the first time. You say:
view.transform = CGAffineTransform(rotationAngle: .pi)
The first time, we change the rotation from 0 to pi. That is a change, so there is animation. But after that we just keep saying “stay at pi” over and over. We are at pi and you say to stay there, so there is no change to animate.
What you want each animation to do is add pi, not be pi.
As #matt suggested, I was merely setting the rotation of the view to .pi over and over. So in the completion block I have now set the transform to .identity before kicking the animation off again.
class AnimatorFactory {
#discardableResult
static func rotateRepeat(view: UIView) -> UIViewPropertyAnimator {
let rotate = UIViewPropertyAnimator(duration: 1.0, curve: .linear)
rotate.addAnimations {
view.transform = CGAffineTransform(rotationAngle: .pi)
}
rotate.addCompletion{ _ in
view.transform = .identity
self.rotateRepeat(view: view)
}
rotate.startAnimation()
return rotate
}
}

Optimizing multiple continuous animations that are heating up device

I’m working on a project that has about 16 UIViews on a ViewController.
Some of the UIView contain some processor intensive CG drawings with transparency done at load time, while other UIView are animating. In particular, the following rotating animations run continuously. (If I look very closely, the animations appear not entirely smooth.)
The device I’m testing on is warming up, it’s not hot, but getting very warm. I’m concerned I’m overloading the processor.
Question:
Is there a more efficient way to complete the below animations which run continuously using a method that is less resource hungry and prevents the device from heating up?
Xcode instruments:
At load (max): CPU: 56% - Memory: 29MB
When running (max): CPU: 1% - Memory: 29MB
func rotateForward() {
UIView.animateWithDuration(2, delay: 0, options: .CurveLinear, animations: { () -> Void in
self.viewA.transform = CGAffineTransformRotate(self.viewA.transform, CGFloat(M_PI_2))
self.viewB.transform = CGAffineTransformRotate(self.viewB.transform, CGFloat(M_PI_2))
self.viewC.transform = CGAffineTransformRotate(self.viewC.transform, CGFloat(M_PI_2))
self.viewD.transform = CGAffineTransformRotate(self.viewD.transform, CGFloat(M_PI_2))
}) { (finished) -> Void in
self.rotateForward()
}
}
func rotateBack() {
UIView.animateWithDuration(2, delay: 0, options: .CurveLinear, animations: { () -> Void in
self.viewW.transform = CGAffineTransformRotate(self.viewW.transform, -CGFloat(M_PI_2))
self.viewX.transform = CGAffineTransformRotate(self.viewX.transform, -CGFloat(M_PI_2))
self.viewY.transform = CGAffineTransformRotate(self.viewY.transform, -CGFloat(M_PI_2))
self.viewZ.transform = CGAffineTransformRotate(self.viewZ.transform, -CGFloat(M_PI_2))
}) { (finished) -> Void in
self.rotateBack()
}
}
Instead of using CPU to run these animation , you can use GPU to perform them.
You can use this protocol to make the view rotate forward. Try to subclass the views to implement this protocol and try it out.
protocol Rotate{ }
extension Rotate where Self: UIView {
func rotate() {
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.duration = 2
animation.repeatCount = Float.infinity
animation.fromValue = 0.0
animation.toValue = Float(M_PI * 2.0)
layer.addAnimation(animation, forKey: "position")
}
}

Custom ease in animateWithDuration?

When doing UIView.animateWithDuration, I would like to define a custom curve for the ease, as opposed to the default: .CurveEaseInOut, .CurveEaseIn, .CurveEaseOut, .CurveLinear.
This is an example ease that I want applied to UIView.animateWithDuration:
let ease = CAMediaTimingFunction(controlPoints: Float(0.8), Float(0.0), Float(0.2), Float(1.0))
I tried making my own UIViewAnimationCurve, but it seems it accepts only one Int.
I can apply the custom ease to a Core Animation, but I would like to have custom easing for UIView.animateWithDuration for simpler and optimized code. UIView.animateWithDuration is better for me as I won't have to define animations for each animated property and easier completion handlers, and to have all animation code in one function.
Here's my non-working code so far:
let customOptions = UIViewAnimationOptions(UInt((0 as NSNumber).integerValue << 50))
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 5)!)
UIView.animateWithDuration(2, delay: 0, options: customOptions, animations: {
view.layer.position = toPosition
view.layer.bounds.size = toSize
}, completion: { finished in
println("completion")
})
That's because UIViewAnimationCurve is an enumeration - its basically human-readable representations of integer values used to determine what curve to use.
If you want to define your own curve, you need to use CA animations.
You can still do completion blocks and groups of animations. You can group multiple CA Animations into a CAAnimationGroup
let theAnimations = CAAnimationGroup()
theAnimations.animations = [positionAnimation, someOtherAnimation]
For completion, use a CATransaction.
CATransaction.begin()
CATransaction.setCompletionBlock { () -> Void in
// something?
}
// your animations go here
CATransaction.commit()
After a bunch of researches, the following code works for me.
Create an explicit core animation transaction, set your desired timing function.
Use eigher or both UIKit and CAAnimation to perform the changes.
let duration = 2.0
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(controlPoints: 0.8, 0.0, 0.2, 1.0))
CATransaction.setCompletionBlock {
print("animation finished")
}
// View animation
UIView.animate(withDuration: duration) {
// E.g. view.center = toPosition
}
// Layer animation
view.layer.position = toPosition
view.layer.bounds.size = toSize
CATransaction.commit()
With iOS 10.0 you can use UIViewPropertyAnimator.
https://developer.apple.com/documentation/uikit/uiviewpropertyanimator
See https://developer.apple.com/videos/play/wwdc2016/216/

How do you repeat an animation in a swift class

Im trying to take my animating function and turn it into its own class.
Can someone help me figure out how to add repeat functionallity? Ive been trying for two days with no luck.
class FlipAnimator {
class func animate(view: UIView) {
let view = view
view.layer.transform = FlipAnimatorStartTransform
view.layer.opacity = 0.8
UIView.animateWithDuration(0.5) {
view.layer.transform = CATransform3DIdentity
view.layer.opacity = 1
}
}
Look at the available signatures for animateWithDuration here. Note that one of them is animateWithDuration(_:delay:options:animations:completion:). Try using .Repeat as the options parameter (a full list of options can be found here).
Specifically:
UIView.animateWithDuration(0.5, delay: 0, options: .Repeat, {
view.layer.transform = CATransform3DIdentity
view.layer.opacity = 1
}, nil)
Note that because animations is not the last parameter you cannot use the trailing closure
syntax.

How do you create a Swift animation class that flips two images

I'm spending my turkey day trying to construct a flip animation class that I have been struggling with for weeks.
The goal is this:
Flip two images repeatedly, quickly at first, then slow down and stop, landing on one of the two images that was chosen before the animation began.
Right now both images are in a container view, in a storyboard. Ive tried using transitionFromView transitionFlipFromTop and I think that could work, but at the time I was unable to get it to repeat.
I am in the process of reading the View Programming Guide, but its tough to connect the dots between it, and swift. Being new to programming in general does not help.
Here is where I'm at: I'm now using a CATransform to scale an image from zero height, to full height. Im thinking that if I can somehow chain two animations, the first one showing the first image scaling up, then back down to zero, then animate the second image doing the same thing, that should give me the first part. Then if I could somehow get those two animations to repeat, quickly at first, then slow down and stop.
It seems I need to know how to nest multiple animations, and then be able to apply an animation curve to the nested animation.
I planned on solving the part about landing on a particular image by having two of these nested animations, one of them would have an odd number of flips, the other an even number of flips. Depending on the desired final image, the appropriate animation gets called.
Right now, my current code is able to repeatedly scale an image from zero to full, a set number of times:
import UIKit
import QuartzCore
let FlipAnimatorStartTransform:CATransform3D = {
let rotationDegrees: CGFloat = -15.0
let rotationRadians: CGFloat = rotationDegrees * (CGFloat(M_PI)/180.0)
let offset = CGPointMake(-20, -20)
var startTransform = CATransform3DIdentity
startTransform = CATransform3DScale(CATransform3DMakeRotation(0, 0, 0, 0),
1, 0, 1);
return startTransform
}()
class FlipAnimator {
class func animate(view: UIView) {
let viewOne = view
let viewTwo = view
viewOne.layer.transform = FlipAnimatorStartTransform
viewTwo.layer.transform = FlipAnimatorStartTransform
UIView.animateWithDuration(0.5, delay: 0, options: .Repeat, {
UIView.setAnimationRepeatCount(7)
viewOne.layer.transform = CATransform3DIdentity
},nil)
}
}
Im going to keep chipping away at it. Any help, or ideas, or hints about a better way to go about it would be amazing.
Thanks.
I'm using this function to rotate image horizontally and to change the image during the transition.
private func flipImageView(imageView: UIImageView, toImage: UIImage, duration: NSTimeInterval, delay: NSTimeInterval = 0)
{
let t = duration / 2
UIView.animateWithDuration(t, delay: delay, options: .CurveEaseIn, animations: { () -> Void in
// Rotate view by 90 degrees
let p = CATransform3DMakeRotation(CGFloat(GLKMathDegreesToRadians(90)), 0.0, 1.0, 0.0)
imageView.layer.transform = p
}, completion: { (Bool) -> Void in
// New image
imageView.image = toImage
// Rotate view to initial position
// We have to start from 270 degrees otherwise the image will be flipped (mirrored) around Y axis
let p = CATransform3DMakeRotation(CGFloat(GLKMathDegreesToRadians(270)), 0.0, 1.0, 0.0)
imageView.layer.transform = p
UIView.animateWithDuration(t, delay: 0, options: .CurveEaseOut, animations: { () -> Void in
// Back to initial position
let p = CATransform3DMakeRotation(CGFloat(GLKMathDegreesToRadians(0)), 0.0, 1.0, 0.0)
imageView.layer.transform = p
}, completion: { (Bool) -> Void in
})
})
}
Don't forget to import GLKit.
This flip animation swift code appears little better:
let transition = CATransition()
transition.startProgress = 0;
transition.endProgress = 1.0;
transition.type = "flip";
transition.subtype = "fromRight";
transition.duration = 0.9;
transition.repeatCount = 2;
self.cardView.layer.addAnimation(transition, forKey: " ")
Other option is
#IBOutlet weak var cardView: UIView!
var back: UIImageView!
var front: UIImageView!
self.front = UIImageView(image: UIImage(named: "heads.png"))
self.back = UIImageView(image: UIImage(named: "tails.png"))
self.cardView.addSubview(self.back)
UIView.transitionFromView(self.back, toView: self.front, duration: 1, options: UIViewAnimationOptions.TransitionFlipFromRight , completion: nil)
Please check link
It seems I need to know how to nest multiple animations, and then be able to apply an animation curve to the nested animation.
I don't think so. I don't think you want/need to nest anything. You are not repeating an animation in this story; you are doing different animations each time (because the durations are to differ). This is a sequence of animations. So I think what you need to know is how to do either a keyframe animation or a grouped animation. That way you can predefine a series of animations, each one lasting a certain predefined duration, each one starting after the preceding durations are over.
And for that, I think you'll be happiest at the Core Animation level. (You can't make a grouped animation at the UIView animation level anyway.)

Resources