I'm trying animate a UIView along a portion of a bezier path. I found a way to move the the view to any part of the path using this code:
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = trackPath.cgPath
animation.rotationMode = kCAAnimationRotateAuto
animation.speed = 0
animation.timeOffset = offset
animation.duration = 1
animation.calculationMode = kCAAnimationPaced
square.layer.add(animation, forKey: "animate position along path")
However, this just moves the view to the desired point and doesn't animate it. How do you animate a view along over a portion of a bezier path?
Thanks
You can accomplish this by modifying the timing of the "complete" animation and a animation group that wraps it.
To illustrate how the timing of such an animation works, imagine – instead of animating a position along a path – that a color is being animated. Then, the complete animation from one color to another can be illustrated as this, where a value further to the right is at a later time — so that the very left is the start value and the very right is the end value:
Note that the "timing" of this animation is linear. This is intentional since the "timing" of the end result will be configured later.
In this animation, imagine that we're looking to animate only the middle third, this part of the animation:
There are a few steps to animating only this part of the animation.
First, configure the "complete" animation to have linear timing (or in the case of an animation along a path; to have a paced calculation mode) and to have a the "complete" duration.
For example: if you're looking to animate a third of the animation an have that take 1 second, configure the complete animation to take 3 seconds.
let relativeStart = 1.0/3.0
let relativeEnd = 2.0/3.0
let duration = 1.0
let innerDuration = duration / (relativeEnd - relativeStart) // 3 seconds
// configure the "complete" animation
animation.duration = innerDuration
This means that the animation currently is illustrated like this (the full animation):
Next, so that the animation "starts" a third of the way into the full animation, we "offset" its time by a third of the duration:
animation.timeOffset = relativeStart * innerDuration
Now the animation is illustrated like this, offset and wrapping from its end value to its start value:
Next, so that we only display part of this animation, we create an animation group with the wanted duration and add only the "complete" animation to it.
let group = CAAnimationGroup()
group.animations = [animation]
group.duration = duration
Even though this group contains an animation that is 3 seconds long it will end after just 1 second, meaning that the 2 seconds of the offset "complete" animation will never be shown.
Now the group animation is illustrated like this, ending after a third of the "complete" animation:
If you look closely you'll see that this (the part that isn't faded out) is the middle third of the "complete" animation.
Now that this group animates animates between the wanted values, it (the group) can be configured further and then added to a layer. For example, if you wanted this "partial" animation to reverse, repeat, and have a timing curve you would configure these things on the group:
group.repeatCount = HUGE
group.autoreverses = true
group.timingFunction = CAMediaTimingFunction(name: "easeInEaseOut")
With this additional configuration, the animation group would be illustrated like this:
As a more concrete example, this is an animation that I created using this technique (in fact all the code is from that example) that moves a layer back and forth like a pendulum. In this case the "complete" animation was a "position" animation along a path that was a full circle
I've done a similar animation just a few days ago:
// I want the animation to go along the circular path of the oval shape
let flightAnimation = CAKeyframeAnimation(keyPath: "position")
flightAnimation.path = ovalShapeLayer.path
// I set this one to make the animation go smoothly along the path
flightAnimation.calculationMode = kCAAnimationPaced
flightAnimation.duration = 1.5
flightAnimation.rotationMode = kCAAnimationRotateAuto
airplaneLayer.add(flightAnimation, forKey: nil)
I see that you set speed to zero and a time offset. Why do you need them?
I would suggest to try the animation using just the parameters in the above code and then try to tune it from them.
Related
I want to animate several properties of several subviews using Core Animations in Swift. I'm looking for a way to group the animations together and handle them as one, mainly to be able to synchronise them altogether and pause and resume all of them together, but also in order to avoid code duplication and make the code cleaner.
I tried to use other kind of animations, such as UIView.animate or UIViewPropertyAnimator, but neither of them fit my needs because they don't allow the customization needed for my case.
For now, I'm using CATransaction to ensure that the animation changes are committed to Core Animation at the same time:
CATransaction.begin()
CATransaction.setAnimationDuration(1.5)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(controlPoints: 0.85, 0, 0.15, 1))
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 0
opacityAnimation.toValue = 1.0
opacityAnimation.repeatCount = .infinity
opacityAnimation.autoreverses = true
self.lable.layer.add(beforeOpacityAnimation, forKey: "opacityAninmation")
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 1.5
scaleAnimation.toValue = 1.0
scaleAnimation.repeatCount = .infinity
scaleAnimation.autoreverses = true
self.imageView.layer.add(targetImageScaleAnimation, forKey: "scaleAnimator")
CATransaction.commit()
So far so good. But now I want to be able to pause and resume all animations together. From what I see here, in order to achieve this one would need to iterate over all animated layers (e.g. self.lable.layer, self.imageView.layer) to modify their speed, timeOffset and beginTime properties (this is kinda dirty and nonatomic).
Is there a way to group these animations or refer to them as one in order to pause and resume them altogether?
If not, should I at least put these iterations over layers inside a CATransaction as well?
I am creating an application wherein I am using SceneKit contents in AR app. I have multiple nodes which are being placed at different places in my scene. They may or may not be necessarily be inside one parent node. The user has to choose a correct node, as per challenge set by the application. If the user chooses correct node, the correct node goes through one kind of animation and incorrect ones (may be several) undergo another set of animation. I am accomplishing animations using CAAnimation directly, which is all good. Basically to accomplish this, I am creating an array of all nodes and using them for animation.
DispatchQueue.global(qos: .userInteractive).async { [weak self] in
for node in (self?.nodesAddedInScene.keys)! {
for index in 1...node.childNodes.count - 1 {
if node.childNodes[index].childNodes.first?.name == "target" {
self?.riseUpSpinAndFadeAnimation(on: node.childNodes[index])
} else {
self?.fadeAnimation(on: node.childNodes[index])
}
}
}
}
When user chooses "target" node, that node goes through one set of animation and others go through another set of animations.
RiseUpSpinAndFadeAnimation:
private func riseUpSpinAndFadeAnimation(on shape: SCNNode) {
let riseUpAnimation = CABasicAnimation(keyPath: "position")
riseUpAnimation.fromValue = SCNVector3(shape.position.x, shape.position.y, shape.position.z)
riseUpAnimation.toValue = SCNVector3(shape.position.x, shape.position.y + 0.5, shape.position.z)
let spinAnimation = CABasicAnimation(keyPath: "eulerAngles.y")
spinAnimation.toValue = shape.eulerAngles.y + 180.0
spinAnimation.autoreverses = true
let fadeAnimation = CABasicAnimation(keyPath: "opacity")
fadeAnimation.toValue = 0.0
let riseUpSpinAndFadeAnimation = CAAnimationGroup()
riseUpSpinAndFadeAnimation.animations = [riseUpAnimation, fadeAnimation, spinAnimation]
riseUpSpinAndFadeAnimation.duration = 1.0
riseUpSpinAndFadeAnimation.fillMode = kCAFillModeForwards
riseUpSpinAndFadeAnimation.isRemovedOnCompletion = false
shape.addAnimation(riseUpSpinAndFadeAnimation, forKey: "riseUpSpinAndFade")
}
FadeAnimation:
private func fadeAnimation(on shape: SCNNode) {
let fadeAnimation = CABasicAnimation(keyPath: "opacity")
fadeAnimation.toValue = 0.0
fadeAnimation.duration = 0.5
fadeAnimation.fillMode = kCAFillModeForwards
fadeAnimation.isRemovedOnCompletion = false
shape.addAnimation(fadeAnimation, forKey: "fade")
}
I expect animations to work out, which they are actually. However, the issue is since the nodes are in an array animation is not being done at the same time for all nodes. There are minute differences in start of animation which actually is leading to not so good UI.
What I am looking for is a logic wherein I can attach animations on all nodes and call these animations together later when let's say the user taps correct node. Arrays don't seem to be a wise choice to me. However, I am afraid if I make all of these nodes child nodes of an empty node and the run animation on that empty node, possibly it would be difficult to manage placement of these child nodes in the first place since they supposed to be kept at random distances and not necessarily close together. Given that this ultimately drives AR experience, it more so becomes a bummer.
Requesting some inputs whether there are methods to attach animation to multiple (selected out of those) object (even if sequentially) but RUN them together. I used shape.addAnimation(fadeAnimation, forKey: "fade") "forKey", can that be made of use in such use case? Any pointers appreciated.
I've had up to fifty SCNNodes animating in perfect harmony by using CAKeyframe animations that are paused (.speed = 0) and setting the animation's time offset (.timeOffset) inside a SCNSceneRendererDelegate "renderer(updateAtTime:)" function.
It's pretty amazing how you can add a paused animation with an time offset every 1/60th of a second for a large number of nodes. Hats off to the SceneKit developers for having so little overhead on adding and removing CAAnimations.
I tried many different CAAnimation/SCNAction techniques before settling on this. In other methods the animations would drift out of sync over time.
Manganese,
I am just taking a guess here or could spark an idea for you :-)
I am focusing on this part of your question:
"What I am looking for is a logic wherein I can attach animations on all nodes and call these animations together later when let's say the user taps correct node."
I wonder if SCNTransaction:
[https://developer.apple.com/documentation/scenekit/scntransaction][1]
might do the trick
or maybe dispatch.sync or async (totally guessing...but could help)
[https://developer.apple.com/documentation/dispatch][1]
or I am way off the mark :-)
just trying to help out....
We all learn by sharing what we know
RAD
I am trying to animate an explosion with CAEmitterLayer and a couple of CAEmitterCell. This should happen after a short delay after user sees a view. I start my animation in viewDidAppear.
Particle animation itself works fine, but as in this question Initial particles from CAEmitterLayer don't start at emitterPosition unless I set emitterLayer.beginTime = CACurrentMediaTime() animation appears to user as one that has been running for some time.
Now to actually achieve an explosion I have to stop emitting particles at some point. I try to use this code to setup CABasicAnimation which would stop emitter after some time:
// emitter layer is reused (remove all animations, remove all cells, remove from superlayer)
... // emitter layer setup in a function "explode" which is called from viewDidAppear
emitterLayer.beginTime = CACurrentMediaTime()
let birthRateAnimation = CABasicAnimation(keyPath: "birthRate")
birthRateAnimation.toValue = 0
birthRateAnimation.timingFunction = CAMediaTimingFunction.init(name:kCAMediaTimingFunctionEaseOut)
birthRateAnimation.beginTime = CACurrentMediaTime() + 1
birthRateAnimation.duration = 5
birthRateAnimation.delegate = self // (self is view controller)
birthRateAnimation.setValue("expl", forKey: "animName")
emitterLayer.add(birthRateAnimation, forKey: "birthRateAnimation")
self.view.layer.addSublayer(emitterLayer)
So now with this code birthRateAnimation is not actually triggered. I have logs in animationDidStop and animationDidStart which don't print anything.
Now, if I call explode function on button tap I see no particle animation at all, but in logs I see "animation start" / "animation stop" messages.
Any idea why?
I found two problems that kept the animation from working correctly.
The animation is on birthRate, but CAEmitterLayer does not have a birthRate property; CAEmitterCell does, though. Give your CAEmitterCell a name and change CABasicAnimation(keyPath: "birthRate") to CABasicAnimation(keyPath: "emitterCells.cellName.birthRate")
Setting the beginTime to CACurrentMediaTime() + 1.0 does not do what you want, because the emitter layer has its own time scale. Changing that to emitterLayer.convertTime(CACurrentMediaTime(), from: nil) + 1.0 does what you want.
Late to the party, but I ran into the very same thing and the solution is to set beginTime of your emitter to CACurrentMediaTime(), e.g.:
let emitter = makeAwesomeEmitter()
emitter.beginTime = CACurrentMediaTime()
let emitterAnimation = makeAwesomeEmitterBirthRateAnimation()
emitterAnimation.beginTime = 1.0 // 1 sec delay
emitter.add(emitterAnimation, forKey: nil)
myView.layer.addSublayer(emitter)
Rationale is that the emitter pre-generates particles to imitate it running already for a while. See also this SO question which brought me to the solution.
I am trying to animate a UIView through non linear path(i'm not trying to draw the path itself) like this :
The initial position of the view is determinated using a trailing and bottom constraint (viewBottomConstraint.constant == 100 & viewTrailingConstraint.constant == 300)
I am using UIView.animatedWithDuration like this :
viewTrailingConstraint.constant = 20
viewBottomConstraint.constant = 450
UIView.animateWithDuration(1.5,animation:{
self.view.layoutIfNeeded()
},completition:nil)
But it animate the view in a linear path.
You can use keyFrame animation with path
let keyFrameAnimation = CAKeyframeAnimation(keyPath:"position")
let mutablePath = CGPathCreateMutable()
CGPathMoveToPoint(mutablePath, nil,50,200)
CGPathAddQuadCurveToPoint(mutablePath, nil,150,100, 250, 200)
keyFrameAnimation.path = mutablePath
keyFrameAnimation.duration = 2.0
keyFrameAnimation.fillMode = kCAFillModeForwards
keyFrameAnimation.removedOnCompletion = false
self.label.layer.addAnimation(keyFrameAnimation, forKey: "animation")
Gif
About this function
void CGContextAddQuadCurveToPoint (
CGContextRef _Nullable c,
CGFloat cpx,
CGFloat cpy,
CGFloat x,
CGFloat y
);
(cpx,cpy) is control point,and (x,y) is end point
Leo's answer of using Core Animation and CAKeyframeAnimation is good, but it operates on the view's "presentation layer" and only creates the appearance of moving the view to a new location. You'll need to add extra code to actually move the view to it's final location after the animation completes. Plus Core Animation is complex and confusing.
I'd recommend using the UIView method
animateKeyframesWithDuration:delay:options:animations:completion:. You'd probably want to use the option value UIViewKeyframeAnimationOptionCalculationModeCubic, which causes the object to move along a curved path that passes through all of your points.
You call that on your view, and then in the animation block, you make multiple calls to addKeyframeWithRelativeStartTime:relativeDuration:animations: that move your view to points along your curve.
I have a sample project on github that shows this and other techniques. It's called KeyframeViewAnimations (link)
Edit:
(Note that UIView animations like animateKeyframes(withDuration:delay:options:animations:completion:) don't actually animate your views along the path you specify. They use a presentation layer just like CALayer animations do, and while the presentation layer makes the view look like it's moving along the specified path, it actually snaps from the beginning position to the end position at the beginning of the animation. UIView animations do move the view to its destination position, where CALayer animations move the presentation layer while not moving the layer/view at all.)
Another subtle difference between Leo's path-based UIView animation and my answer using UIView animateKeyframes(withDuration:delay:options:animations:completion:)is that CGPath curves are cubic or quadratic Bezier curves, and my answer animates using a different kind of curve called a Katmull-Rom spline. Bezier paths start and end at their beginning and ending points, and are attracted to, but don't pass through their middle control points. Catmull-Rom splines generate a curve that passes through every one of their control points.
I have an animation in my SceneKit project. It animates the node that is pressed. Now, the animation works with this code:
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
SCNTransaction.setCompletionBlock {
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
result.node!.position.y -= 1
SCNTransaction.commit()
}
result.node!.position.y += 1
SCNTransaction.commit()
}
I want to make the node seem like it is jumping, therefore I would like to use some animation options, such as you can use with a UIView: CurveEaseIn etc.. (I want it to start slowly, end abrupt. The second should be abrupt first, then slowly.)
Is there a way to use these for a SCNTransaction? Or is there maybe a better way to make it 'bounce'?
Thanks in advance :)
Changing the timing function
Yes, you can change the timing function with SCNTransaction.
You do that by creating a CAMediaTimingFunction object and assigning it using setAnimationTimingFunction(). There are a couple of named timing functions (for example "ease in"), or you can create one using two set of control points.
let easeIn = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
SCNTransaction.setAnimationTimingFunction(easeIn)
Using a key-frame animation
Another alternative is to create a more custom key-frame animation for the node's y-position. I did a bounce looking key-frame animation in the sample code for Chapter 5 of my book about Scene Kit:
var jump = CAKeyframeAnimation(keyPath: "position.y")
let easeIn = CAMediaTimingFunction(controlPoints: 0.35, 0.0, 1.0, 1.0)
let easeOut = CAMediaTimingFunction(controlPoints: 0.0, 1.0, 0.65, 1.0)
jump.values = [0.000000, 0.433333, 0.000000, 0.124444, 0.000000, 0.035111, 0.000000];
jump.keyTimes = [0.000000, 0.255319, 0.531915, 0.680851, 0.829788, 0.914894, 1.000000];
jump.timingFunctions = [easeOut, easeIn, easeOut, easeIn, easeOut, easeIn ];
jump.duration = 0.783333;
yourNodeThatWasClicked.addAnimation(jump, forKey: "jump and bounce")
If you go down this path, I would recommend finding somewhere that you can experiment, tweak, and play with the key times and values of the key-frame animation. Perhaps a playground or a small custom app with sliders where you can get fast iterations.
you can use a CABasicAnimation with byValue of 1 and set autoreverses to YES. Finally set its timingFunction to kCAMediaTimingFunctionEaseIn (or, more specifically, a timing function initialized with this curve name).