I'm currently creating a small button with two different states. Every state is represented by two CAShapeLayers and the transition between the states is animated with a series of CAKeyframeAnimations/CABasicAnimations, which all change the path property of the shape layers. My question is how do I animate to a state starting from a current animation (i.e. button is pressed while animating).
Normally, I would ask the presentation layer for the current property value and use an additive animation (as perfectly described here), but since this is a multi-step animation I would have to figure out which step I am currently animating and then chain the appropriate animation to reverse to the previous state. But that is rather tricky (I wanted to have all the animation be removeOnCompletion=false and query the time offset of the animations to figure out which animation is currently active and how far).
Unfortunately, setting the layer speed to 0.0 and just animating the timeOffset back and forth doesn't work either, since I have secondary animations which behave differently in the opposite direction.
Using a custom layer property for the shape layers seems cumbersome, but I could match a progress property more easily to the current animation step.
So after some trial and error I come up with the following "solution": I use a CADisplayLink to get a time update for every frame and by subtracting the current timestamp from the timestamp when the animation started, I can figure out the elapsed animation time, thus the progress (by dividing through animationDuration). That way I can start the reverse animation with an offset. Internally, I calculate the next frame from the keyframe animation and adjust the keyTimes for the new duration.
You can see an implementation of this here
Related
Lets assume I have some input function which decides which direction to run. The atlas file being referenced to the game object has 8 (isometric) walk animations (same frame count, one animation per 1/8 rotation). Thus, if the rotation changes I want to set another animation but with its cursor at the same time (For the user the object should only rotate without starting the animation again)
I tried to do the following in the on_input function
self.cursor = go.get("#sprite", "cursor")
msg.post('#sprite','play_animation',{id = hash('run_5')})
go.set("#sprite", "cursor", cursor)
which is obviously not working because msg.post is async thus line 3 runs after 2 is being executed. How to get this done properly?
You can find some solutions here: at defold-forum.I can't write comments, so I had to write here.
let flyRight = CABasicAnimation(keyPath: "position.x")
flyRight.toValue = view.bounds.size.width/2
flyRight.duration = 0.5
flyRight.fromValue = -view.bounds.size.width/2
flyRight.fillMode = kCAFillModeBoth
flyRight.beginTime = CACurrentMediaTime() + 3.4
password.layer.position.x = view.bounds.size.width/2
password.layer.addAnimation(flyRight, forKey: nil)
My question is: how is it possible that before I am adding the animation, I first put the layer at the end position, but when the app goes up, I don't see it there before the animation starts? Instead, the animation works after 3.4 seconds as expected.
I mean, how iOS knows that first it needs to run the animation and only then put the layer to it's final position?
This is because there is a presentationLayer and a modelLayer so animation show and modify presentationLayer, so presentationLayer is like a ghost.
You probably know that UIView instances, as well as layer-backed NSViews, modify their layer to delegate rendering to the powerful Core
Animation framework. However, it is important to understand that
animations, when added to a layer, don’t modify its properties
directly.
Instead, Core Animation maintains two parallel layer hierarchies: the model layer tree and the presentation layer tree.
Layers in the former reflect the well-known state of the layers, wheres only layers in the latter approximate the in-flight values of
animations.
Consider adding a fade-out animation to a view. If you, at any point during the animation, inspect the layer’s opacity value, you
most likely won’t get an opacity that corresponds to what is onscreen.
Instead, you need to inspect the presentation layer to get the correct
result.
While you may not set properties of the presentation layer directly, it can be useful to use its current values to create new
animations or to interact with layers while an animation is taking
place.
By using -[CALayer presentationLayer] and -[CALayer modelLayer], you can switch between the two layer hierarchies with ease.
you can find more info here https://www.objc.io/issues/12-animations/animations-explained/
I hope this helps you
It has to do with the way UI changes get applied. When you make a change to a UI object, that change is not rendered to the screen until your code returns and the event loop runs.
When that happens, the system moves your view to it's final position, but then the ACTUAL view/layer hierarchy gets covered with a new layer that's drawn on top, known as the presentation layer. The presentation layer is where the pixels from the animation show up on the screen. That's what you see.
When the animation finishes, the presentation layer is hidden/removed (not honestly sure which) and the actual layer contents are shown. At that point the layer is in it's final position, so everything looks correct.
I'm wondering if the following is possible with CoreAnimation.
Like the title says, I'd like to animate or seek if you will, to a position in time over an entire timeline animation.
For example, say I create a CABasicAnimation which animates a CALayer's color from blue to red over an entire timeline of 10 seconds with an easing function of EaseOut.
Rather than playing that animation from start to finish, I'd prefer finer control.
For example, I'd like to say animateTo(50%) of the entire animation. This would result in an animation starting at 0% and animating to 50% of the entire animation with an ease out function. So the animation would last 5 seconds and we'd be in the middle of our color transform.
After this I could say, animateTo(20%). This would result in an animation starting from our current position of 50% and animating in reverse to 20% of the total animation. So we'd end up with a 3 second animation and we'd be 20% into our color transform from blue to red.
In the end we're just animating to a position in time over the entire timeline. I could easily say animateTo(5 seconds) rather than animateTo(50%). Or animateTo(2 seconds) rather than animateTo(20%).
I've been reading up on CoreAnimation and it appears I am un-able to get this kind of control. Has anyone else tried this with CoreAnimation?
Thanks!
The latest SDK adds a bit to UIKit animation.
It might suit your needs...
According to the documentation:
New object-based, fully interactive and interruptible animation support that lets you retain control of your animations and link them with gesture-based interactions
The new shiny UIViewPropertyAnimator:
let animator = UIViewPropertyAnimator(duration: 3.0, curve: .easeInOut) {
self.myView.alpha = 0
}
animator.startAnimation()
animator.pauseAnimation()
animator.isReversed = true
animator.fractionComplete = 1.5 / CGFloat(animator.duration)
However there are some limitations:
The PropertyAnimator requires targeting iOS 10 (which is still in beta as at the time of writing).
Also the animations are limited to UIView Animatable Properties, which are:
frame
bounds
center
transform
alpha
backgroundColor
contentStretch
If you seek more flexibility and features take a look at some open source libraries like TRX and Advance:
import TRX
let tween = Tween(from: 0, to: 1, time:3, ease:Ease.Quad.easeOut) {
anyObject.anyProperty = $0
}
let reversed = tween.reversed()
reversed.seek(1.5)
reversed.start()
As already pointed out, there is no built-in function. But if you want to create your own solution, here are a few notes and useful functions that are already there.
The CABasicAnimation conforms to the `CAMediaTiming´ protocol and contains some neat functionality for your use case:
timeOffset - this value determines at what time into the animation you actually want to start, if you have a animation with a duration of 2 seconds and timeOffset set to 1, it will cause the animation to start in the middle.
speed - setting that value to -1 would cause the animation to reverse (e.g. for the case of from 50% to 20%)
duration - might be changed if you want to change the duration of the animation for shorter changes e.g. form 40% to 50%.
timingFunction - I was hoping it might be possible to provide a custom timing function here, which for example just completes the animation after 1 second even if the duration is set to be 5 seconds, meaning: a linear function between 0 and 1 and after that just constant. It may however be possible to achieve an approximation of that with a bezierPath as well.
I'm currently implementing a CABasicAnimation that animates a CALayer transform property.
Now, although I'm new to Core Animation, I have been able to gather through various blogs and articles such as objc.io that it is a very bad idea to use the often (incorrectly) recommended method for getting animations to stick using the fillMode and removedOnCompletion properties of an animation. This method is considered bad practice by many because it creates a discrepancy between the model layer and the presentation layer, and so future queries to one of those layers may not match up with what the user is seeing.
Instead, the recommended way of doing animations is to update the model layer at the same time you add the animation to the layer being animated. However, I'm having trouble understanding exactly how this is working. My animation is simple, and goes like this:
CATransform3D updatedTransform = [self newTransformWithCurrentTransform];
// Location 1
CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:#"transform"];
transformAnimation.duration = 1;
transformAnimation.fromValue = [NSValue valueWithCATransform3D:self.layerBeingAnimated.transform]; // Does not work without this.
transformAnimation.toValue = [NSValue valueWithCATransform3D:updatedTransform];
// Location 2
[self.layerBeingAnimated addAnimation:transformAnimation forKey:kTransformAnimationKey];
// Location 3
I've denoted three locations where I have attempted to update the model layer using the code
self.layerBeingAnimated.transform = updatedTransform;
In location 1, the layer jumps right to newTransform and does not animate.
In location 2, the layer animates exactly as I want it to from the current transform to newTransform.
In location 3, the layer jumps right to newTransform, jumps back to the the old transform, animates correctly from the fromValue to newTransform, and then stays at newTransform.
What's the deal here? What's the correct location to update the model layer and why are these three locations producing such different results?
Thanks!
I think that it's easiest to explain what is happening for each of the three locations and then a "conclusion" at the end.
I'm also adding some illustrations, showing exactly the behaviour that you are mentioning in your question so that it will be easier to follow for someone who hasn't tried these three things themselves. I'm also extending the illustration to show both a stand alone layer and a backing layer (one that is attached to a view) and I will explain the difference where there is one.
Location 1
In the first location, the model value is updated before the animation is created. Once this is done, the transform property holds the updatedTransform. This means that when you read the transform from the layer for the fromValue, you get the updatedValue back. This in turn means that both to and from value are the same so you can't see the animation.
One thing that could have made this location work as expected is to read the oldValue before assigning the new value and then use that as the fromValue. This will look as expected.
// Location 1
CATransform3D oldValue = layer.transform; // read the old value first
layer.transform = updatedTransform; // then update to the new value
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"transform"];
anim.duration = 1.0;
anim.fromValue = [NSValue valueWithCATransform3D:oldValue];
anim.toValue = [NSValue valueWithCATransform3D:updatedTransform];
Location 2
In the second example, the value isn't yet updated when you read the transform for the from value, so the fromValue and toValue are different. After that, the model value is updated to it's final value. There is actually a difference between the stand-alone layer and the backing layer here, but we don't see it. The transform property on CALayer is animatable and will automatically perform an "implicit" animation when the value changes. This means that an animation will be added to the layer for the "transform" key path. The view, however, disables this behaviour when the change happens outside of an animation block, so there is not implicit animation there.
The reason why we don't see the implicit animation is that the "explicit" animation is added afterwards for the same key path. This means that the only explicit animation will be visible, in both cases, even thought there are two animation running on the stand-alone layer (more on that later). If you are feeling cautious, then you could disable the implicit action for the stand-alone layer (more on that later).
Location 3
This leaves us with the last location. In this case the animation is created just as above, with different fromValue and toValue. The only difference is the order of adding the explicit animation and changing the property which triggers an implicit animation. In this case the implicit animation is added after the explicit animation and they both run(!). Both animations actually ran for location 2, but we couldn't see it because the explicit (longer) animation was added before.
Since everything is moving so fast, I slowed down the entire layer to try and illustrate what is happening when two animations are running at once. This way it becomes much easier to see what happens when the implicit animation ends. I've overlaid the well behaving backing layer and the misbehaving stand-alone layer and made them both 50% transparent. The dashed outline is the original frame.
A short description of what is happening: the blue view get's only the explicit animation added to it (which has a 1 second duration). The orange layer first has the same explicit animation added to it and then has an implicit 0.25 second animation added to it. Neither explicit nor the implicit animations are "additive", meaning their toValue and fromValue are used as-is.
Disclaimer: I do not work at Apple and I haven't seen the source code for Core Animation so what I'm about to say is guesswork based on how things behave.
In my understanding (see disclaimer) this is what happens for every screen refresh to produce the animation: for the current time stamp, the layer goes through the animations in the order they were added and updates the presentation values. In this case, the explicit animation sets a rotation transform, then the implicit animation comes and sets another rotation transform that completely overrides the explicit transform.
If an animation is configured to be "additive", it will add to the presentation values instead of overwriting (which is super powerful). Even with additive animations, order still matters. A non-additive animation could come later and overwrite the whole thing.
Since the implicit animation is shorter than the explicit one, we see that for the first part of the total animation, the values are strictly coming from the implicit animation (which was added last). Once the implicit animation finishes, the only remaining animation is the explicit animation which has been running underneath the implicit one, all this time. So when the implicit animation finishes, the explicit animation has already progressed 0.25 seconds and we see that the orange layer jumps back to the same value as the blue view, instead of jumping back to the beginning.
Where should we update the value?
At this point, the question is, how can we prevent two animations from being added and where should we update the value? The location where the value is updated doesn't prevent there from being two animations (but it can affect how the end result looks).
To prevent two actions from being added to the stand-alone layer, we temporarily disable all "actions" (a more general term for an animation):
[CATransaction begin];
[CATransaction setDisableActions:YES]; // actions are disabled for now
layer.transform = updatedTransform;
[CATransaction commit]; // until here
When we do this, only one animation is added to the layer so either location 2 or 3 works. That is simply a matter of taste. If you read the oldValue, the you can also use location 1 (as long as the action is disabled).
If you are animating a backing layer then you don't have to disable actions (the view does that for you) but it also doesn't hurt to do so.
At this point I could keep going about other ways to configure an animation, what an additive animation is, and why you needed to specify both the toValue and fromValue in this case. But I think that I have answered the question you asked and that this answer already is a bit on the long side.
I want to build an animated transition between two view controllers in iOS, resembling the "Box" transition in PowerPoint or the "Reflection" transition in Keynote.
You can see it here, at 2:10:
http://youtu.be/1fLQg5hFQQg?t=2m10s
What's the best way to do this?
Thanks!
That would be a complex animation to recreate. You'd need to use a CAAnimationGroup that grouped several different animations running at once. You'd want to animate a rotation around the y axis with the center of rotation lifted off the screen, on both the view controller that is animating away and the view that your are animating into place.
You would have to tweak the transform to make it draw with perspective (you add a small value to the .m34 record in the transform). That's because CA animations are orthographic by default (they don't show perspective.)
The reflections could be created using a special subclass of CALayer that lets you create duplicates of a layer. I'm blanking on the name of that layer subclass at the moment. You'd set up 1 duplicate with a scale of -1 on the y axis to flip it upside down, and a darkening effect. I've never done it myself, but I've seen several examples in books and online.