execute animation when access to a property - core-animation

this is a simple code form Brad Larson u-tunes course ;)
CABasicAnimation *move = [CABasicAnimation animationWithKeyPath:#"position"];
move.duration = 1.0f;
move.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
move.removedOnCompletion = NO;
move.fillMode = kCAFillModeForwards;
CGPoint currentPosition = l.position;
CGPoint newPosition = CGPointMake(currentPosition.x + 60.0f, currentPosition.y + 60.0f);
move.toValue = [NSValue valueWithCGPoint:newPosition];
[l addAnimation:move forKey:#"position"];
l.position = newPosition;
in the last row i change the position to reflect the final state of layer because animation does not.
But when i execute this code the animation isn't executed and layer move (in 1/4 of sec) to newposition.
someone can explain me how to animate layer's position correctly?
a second question...when i run this code...every subsequent access to property "position" will perform the same animation?
thanks.

Ditch the last line, the l.position = newPosition;. Your animation will already take care of that, and by using that property setter, you’re implicitly giving the layer Core Animation’s default .25-second action.
Also, no, subsequent changes in the position of your layer will not use your 1-second animation. The properties you’re using look pretty much identical to the default animation, though, aside from the duration; a quicker way to accomplish what you’re doing would be something like this.
CGPoint currentPosition = l.position;
CGPoint newPosition = CGPointMake(currentPosition.x + 60.0f, currentPosition.y + 60.0f);
[CATransaction begin];
[CATransaction setAnimationDuration:1.0];
l.position = newPosition;
[CATransaction commit];

Related

Creating animated layer stroke

I want to create something like this, just consider single loop and how it completes a circle and reverse it on completion:
This piece of code does half of what I want:
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:#"strokeStart"];
drawAnimation.duration = 1;
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue = [NSNumber numberWithFloat:1.0f];
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[circleLayer addAnimation:drawAnimation forKey:#"drawCircleAnimation"];
I tried it to reverse but does not work:
[CATransaction begin];
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:#"strokeStart"];
drawAnimation.duration = 1;
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue = [NSNumber numberWithFloat:1.0f];
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
//[circleLayer addAnimation:drawAnimation forKey:#"drawCircleAnimation"];
[CATransaction setCompletionBlock:^{
CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
animation2.duration = 1;
animation2.fromValue = [NSNumber numberWithFloat:0.0f];
animation2.toValue = [NSNumber numberWithFloat:1.0f];
animation2.removedOnCompletion = NO;
animation2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[circleLayer addAnimation:animation2 forKey:#"circelBack"];
}];
[circleLayer addAnimation:drawAnimation forKey:#"circleFront"];
[CATransaction commit];
The problem is I cannot reverse the animation.
The Problem
First of all, I suspect you've got the key paths of your animations round the wrong way. You should first be animating the stroke end from 0 to 1, and then the stroke start from 0 to 1.
Secondly, you're never updating the model layer with your new values - so when the animation is complete, the layer will 'snap back' to its original state. For you, this means that when the first animation is done - the strokeStart will snap back to 0.0 - therefore the reverse animation will look weird.
The Solution
To update the model layer values, you can simply set disableActions to YES in your CATransaction block to prevent an implicit animations from being generated on layer property changes (won't affect explicit animations). You'll then want to update the model layer's property after you add the animation to the layer.
Also, you can re-use CAAnimations – as they are copied when added to a layer. Therefore you can define the same animation for both the forward and reverse animation, just changing the key path.
If you're repeating the animation, you'll probably want to define your animation as an ivar - and simply update the key path before adding it.
For example, in your viewDidLoad:
#implementation ViewController {
CABasicAnimation* drawAnimation;
}
- (void)viewDidLoad {
[super viewDidLoad];
// define your animation
drawAnimation = [CABasicAnimation animation];
drawAnimation.duration = 1;
// use an NSNumber literal to make your code easier to read
drawAnimation.fromValue = #(0.0f);
drawAnimation.toValue = #(1.0f);
// your timing function
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
// kick off the animation loop
[self animate];
}
You'll then want to create an animate method in order to perform one iteration of the animation. Unfortunately, since Core Animation doesn't support repeating multiple animations in a sequence, you'll have to use recursion to achieve your effect.
For example:
-(void) animate {
if (self.circleLayer.superlayer) { // check circle layer is the layer heirachy before attempting to animate
// begin your transaction
[CATransaction begin];
// prevent implicit animations from being generated
[CATransaction setDisableActions:YES];
// reset values
self.circleLayer.strokeEnd = 0.0;
self.circleLayer.strokeStart = 0.0;
// update key path of animation
drawAnimation.keyPath = #"strokeEnd";
// set your completion block of forward animation
[CATransaction setCompletionBlock:^{
// weak link to self to prevent a retain cycle
__weak typeof(self) weakSelf = self;
// begin new transaction
[CATransaction begin];
// prevent implicit animations from being generated
[CATransaction setDisableActions:YES];
// set completion block of backward animation to call animate (recursive)
[CATransaction setCompletionBlock:^{
[weakSelf animate];
}];
// re-use your drawAnimation, just changing the key path
drawAnimation.keyPath = #"strokeStart";
// add backward animation
[weakSelf.circleLayer addAnimation:drawAnimation forKey:#"circleBack"];
// update your layer to new stroke start value
weakSelf.circleLayer.strokeStart = 1.0;
// end transaction
[CATransaction commit];
}];
// add forward animation
[self.circleLayer addAnimation:drawAnimation forKey:#"circleFront"];
// update layer to new stroke end value
self.circleLayer.strokeEnd = 1.0;
[CATransaction commit];
}
}
To stop the animation, you can remove the layer from the superlayer - or implement your own boolean check for whether the animation should continue.
Full Project: https://github.com/hamishknight/Circle-Pie-Animation

What's the easiest way to animate a line?

I am creating an app that involves animating lines within a workspace over time. My current approach for this is to use code like this in drawRect:
CGContextSetStrokeColor(context, black);
CGContextBeginPath(context);
CGContextMoveToPoint(context, startPoint.x, startPoint.y);
CGContextAddLineToPoint(context, finalPoint.x, finalPoint.y);
CGContextStrokePath(context);
...and then just setting a timer to run every 0.05 seconds to update finalPoint and call setNeedsDisplay.
I'm finding this approach (when there's 5ish lines moving at once) slows down the app terribly, and even with such a high refresh frequency, still appears jerky.
There must be some better way to perform this very simple line drawing in an animated line - i.e. saying that I want a line to start at x1, y1 and stretching to x2, y2 over a given length of time. What are my options for this? I need to make this perform faster and would love to get rid of this clunky timer.
Thanks!
Use CAShapeLayers, and a combination of CATransactions and CABasicAnimation.
You can add a given path to a shapeLayer and let it do the rendering.
A CAShapeLayer object has two properties called strokeStart and strokeEnd, which defines where along the path the end of the line should render. The defaults are 0.0 for strokeStart, and 1.0 for strokeEnd.
If you set up your path so that strokeEnd initially starts at 0.0, you will see no line.
You can then animate, from 0.0 to 1.0, the strokeEnd property and you will see the line lengthen.
To change CAShapeLayer's implicit 0.25s default animation timing, you can add a function to the class, like so:
-(void)animateStrokeEnd:(CGFloat)_strokeEnd {
[CATransaction begin];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:keyPath];
animation.duration = 2.0f; //or however long you want it to happen
animation.fromValue = [NSNumber numberWithFloat:self.strokeEnd]; // from the current strokeEnd value
animation.toValue = [NSNumber numberWithFloat:_strokeEnd]; //to the end of the path
[CATransaction setCompletionBlock:^{ self.strokeEnd = _strokeEnd }];
[self addAnimation:animation forKey:#"animateStrokeEnd"];
[CATransaction commit];
}
You can pass any value from 0.0f to 1.0f as the value of _strokeEnd.
The setCompletionBlock: ensures that the value you are passing is explicitly set after the animation completes.

Animating Views with Core Animation Layer

I have a NSWindow containing a NSView with 'Wants Core Animation Layer' enabled. The view then contains many NSImageView that use are initially animated into position. When I run the animation, it is extremely sluggish and drops most of the frames. However, if I disable 'Wants Core Animation Layer' the animation works perfectly. I'm going to need the core animation layer but can't figure out how to get it to perform adequately.
Can I do anything to fix the performance issues?
Here is the code:
// AppDelegate
NSRect origin = ...;
NSTimeInterval d = 0.0;
for (id view in views)
{
[view performSelector:#selector(animateFrom:) withObject:origin afterDelay:d];
d += 0.05f;
}
// NSImageView+Animations
- (void)animateFrom:(NSRect)origin
{
NSRect original = self.frame;
[self setFrame:origin];
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.20f];
[[self animator] setFrame:original];
[NSAnimationContext endGrouping];
}
It's possible that the NSTimer is killing your performance. Core Animation has rich support for controlling the timing of animations through the CAMediaTiming protocol, and you should take advantage of that in your app. Instead of using the animator proxy and NSAnimationContext, try using Core Animation directly. If you create a CABasicAnimation for each image and set its beginTime, it will delay the start of the animation. Also, for the delay to work the way you want, you must wrap each animation in a CAAnimationGroup with its duration set to the total time of the entire animation.
Using the frame property could also be contributing to the slowdown. I really like to take advantage of the transform property on CALayer in situations like this where you're doing an "opening" animation. You can lay out your images in IB (or in code) at their final positions, and right before the window becomes visible, modify their transforms to the animation's starting position. Then, you just reset all of the transforms to CATransform3DIdentity to get the interface into its normal state.
I have an example in my <plug type="shameless"> upcoming Core Animation book </plug> that's very similar to what you're trying to do. It animates 30 NSImageViews simultaneously with no dropped frames. I modified the example for you and put it up on github. These are the most relevant bits of code with the extraneous UI stuff stripped out:
Transform the layers to their start position
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// ... SNIP ... //
//Start with all of the images at the origin
[CATransaction begin];
[CATransaction setDisableActions:YES];
for (CALayer *imageLayer in [[[self imageContainer] layer] sublayers]) {
CGPoint layerPosition = [layer position];
CATransform3D originTransform = CATransform3DMakeTranslation(20.f - layerPosition.x, -layerPosition.y, 0.f);
[imageLayer setTransform:originTransform];
}
[CATransaction commit];
}
Animate the transform back to the identity
- (IBAction)runAnimation:(id)sender {
CALayer *containerLayer = [[self imageContainer] layer];
NSTimeInterval delay = 0.f;
NSTimeInterval delayStep = .05f;
NSTimeInterval singleDuration = [[self durationStepper] doubleValue];
NSTimeInterval fullDuration = singleDuration + (delayStep * [[containerLayer sublayers] count]);
for (CALayer *imageLayer in [containerLayer sublayers]) {
CATransform3D currentTransform = [[imageLayer presentationLayer] transform];
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"transform"];
anim.beginTime = delay;
anim.fromValue = [NSValue valueWithCATransform3D:currentTransform];
anim.toValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
anim.fillMode = kCAFillModeBackwards;
anim.duration = singleDuration;
CAAnimationGroup *group = [CAAnimationGroup animation];
group.animations = [NSArray arrayWithObject:anim];
group.duration = fullDuration;
[imageLayer setTransform:CATransform3DIdentity];
[imageLayer addAnimation:group forKey:#"transform"];
delay += delayStep;
}
}
I also have a video on YouTube of the example in action if you want to check it out.
Did you try to batch everything in a CATransaction?
[CATransaction begin];
for {...}
[CATransaction commit];
CATransaction is the Core Animation mechanism for batching multiple layer-tree operations into atomic updates to the render tree.

How to add an animated layer at a specific index

I am adding two CAText layers to a view and animating one of them. I want to animate one layer above the other but it doesn't get positioned correctly in the layer hierarchy until the animation has finished. Can anyone see what I have done wrong? The animation works, it is just running behind 'topcharlayer2' until the animation has finished.
- (CABasicAnimation *)topCharFlap
{
CABasicAnimation *flipAnimation;
flipAnimation = [CABasicAnimation animationWithKeyPath:#"transform"];
flipAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(1.57f, 1, 0, 0)];
flipAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.0, 1, 0, 0)];
flipAnimation.autoreverses = NO;
flipAnimation.duration = 0.5f;
flipAnimation.repeatCount = 10;
return flipAnimation;
}
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self setBackgroundColor:[UIColor clearColor]]; //makes this view transparent other than what is drawn.
[self initChar];
}
return self;
}
static CATransform3D CATransform3DMakePerspective(CGFloat z)
{
CATransform3D t = CATransform3DIdentity;
t.m34 = - 1. / z;
return t;
}
-(void) initChar
{
UIFont *theFont = [UIFont fontWithName:#"AmericanTypewriter" size:FONT_SIZE];
self.layer.sublayerTransform = CATransform3DMakePerspective(-1000.0f);
topHalfCharLayer2 = [CATextLayer layer];
topHalfCharLayer2.bounds = CGRectMake(0.0f, 0.0f, CHARACTERS_WIDTH, 100.0f);
topHalfCharLayer2.string = #"R";
topHalfCharLayer2.font = theFont.fontName;
topHalfCharLayer2.fontSize = FONT_SIZE;
topHalfCharLayer2.backgroundColor = [UIColor blackColor].CGColor;
topHalfCharLayer2.position = CGPointMake(CGRectGetMidX(self.bounds),CGRectGetMidY(self.bounds));
topHalfCharLayer2.wrapped = NO;
topHalfCharLayer1 = [CATextLayer layer];
topHalfCharLayer1.bounds = CGRectMake(0.0f, 0.0f, CHARACTERS_WIDTH, 100.0f);
topHalfCharLayer1.string = #"T";
topHalfCharLayer1.font = theFont.fontName;
topHalfCharLayer1.fontSize = FONT_SIZE;
topHalfCharLayer1.backgroundColor = [UIColor redColor].CGColor;
topHalfCharLayer1.position = CGPointMake(CGRectGetMidX(self.bounds),CGRectGetMidY(self.bounds));
topHalfCharLayer1.wrapped = NO;
//topHalfCharLayer1.zPosition = 100;
[topHalfCharLayer1 setAnchorPoint:CGPointMake(0.5f,1.0f)];
[[self layer] addSublayer:topHalfCharLayer1 ];
[[self layer] insertSublayer:topHalfCharLayer2 atIndex:0];
[topHalfCharLayer1 addAnimation:[self topCharFlap] forKey:#"anythingILikeApparently"];
}
The View which contains this code is loaded by a view controller in loadView. The initChar method is called in the view's initWithFrame method. The target is iOS4. I'm not using setWantsLayer as I've read that UIView in iOS is automatically layer backed and doesn't require this.
A couple thoughts come to mind:
Try adding the 'R' layer to the layer hierarchy before you start the animation.
Instead of inserting the 'T' layer at index 1, use [[self layer] addSublayer: topHalfCharLayer1]; to add it and then do the insert for the 'R' layer with [[self layer] insertSublayer:topHalfCharLayer2 atIndex:0];
Have you tried to play with the layer zPosition? This determines the visual appearance of the layers. It doesn't actually shift the layer order, but will change the way they display--e.g. which layers is in front of/behind which.
I would also suggest you remove the animation code until you get the layer view order sorted. Once you've done that, the animation should just work.
If you have further issues, let me know in the comments.
Best regards.
From the quartz-dev apple mailing list:
Generally in a 2D case, addSublayer will draw the new layer above the
previous. However, I believe this implementation mechanism is
independent of zPosition and probably just uses something like
painter's algorithm. But the moment you add zPositions and 3D, I don't
think you can solely rely on layer ordering. But I am actually unclear
if Apple guarantees anything in the case where you have not set
zPositions on your layers but have a 3D transform matrix set.
So, it seems I have to set the zPosition explicitly when applying 3D transforms to layers.
/* Insert 'layer' at position 'idx' in the receiver's sublayers array.
* If 'layer' already has a superlayer, it will be removed before being
* inserted. */
open func insertSublayer(_ layer: CALayer, at idx: UInt32)

Animate CALayer hide

I'm trying to hide a CALayer after a few microseconds and I'm using CABasicAnimation to animate the hide.
At the moment I'm trying to use
[aLayer setHidden:YES];
CABasicAnimation * hideAnimation = [CABasicAnimation animationWithKeyPath:#"hidden"];
[hideAnimation setDuration:aDuration];
[hideAnimation setFromValue:[NSNumber numberWithBool:NO]];
[hideAnimation setToValue:[NSNumber numberWithBool:YES]];
[hideAnimation setBeginTime:0.09];
[hideAnimation setRemovedOnCompletion:NO];
[hideAnimation setDelegate:self];
[alayer addAnimation:hideAnimation forKey:#"hide"];
But when I run this, the layer is hidden immediately, rather than waiting for the desired beginTime.
I'm uncertain about my keyPath as "hidden" but couldn't find any other option and the documentation does state that the hidden property of a CALayer is animatable.
What's the correct way to achieve what I'm looking for?
Try animating the opacity property instead. Go from 1.0 to 0.0 and you should get the effect you want.
From CAMediaTiming.h, it says about beginTime property:
The begin time of the object, in
relation to its parent object, if
applicable. Defaults to 0.
You should use CACurrentMediaTime() + desired time offset.
[hideAnimation setBeginTime:CACurrentMediaTime() + 0.09];
I'm sure this is too late to do the original poster any good, but it may help others. I've been trying to do something similar, except to make the animation implicit when the hidden property is changed. As Tom says, animating opacity doesn't work in that case, as the change to the layer's hidden property seems to take effect right away (even if I delay the animation with beginTime).
The standard implicit action uses a fade transition (CATransition, type = kCATransitionFade), but this operates on the whole layer and I want to perform another animation at the same time, which is not a compatible operation.
After much experimentation, I finally noticed #Kevin's comment above and --- hello! --- that actually works! So I just wanted to call it out so the solution is more visible to future searchers:
CAKeyframeAnimation* hiddenAnim = [CAKeyframeAnimation animationWithKeyPath:#"hidden"];
hiddenAnim.values = #[#(NO),#(YES)];
hiddenAnim.keyTimes = #[#0.0, #1.0];
hiddenAnim.calculationMode = kCAAnimationDiscrete;
hiddenAnim.duration = duration;
This delays the hiding until the end of the duration. Combine it with other property animations in a group to have their effects seen before the layer disappears. (You can combine this with an opacity animation to have the layer fade out, while performing another animation.)
Thank you, Kevin!
swift 4
let keyframeAnimation = CAKeyframeAnimation(keyPath: "hidden")
keyframeAnimation.calculationMode = kCAAnimationDiscrete
keyframeAnimation.repeatCount = 1.0
keyframeAnimation.values = [true, false,true,false,true]
keyframeAnimation.keyTimes = [0.0, 0.25,0.5,0.75, 1.0]
keyframeAnimation.duration = 30.0 //duration of the video in my case
keyframeAnimation.beginTime = 0.1
keyframeAnimation.isRemovedOnCompletion = false
keyframeAnimation.fillMode = kCAFillModeBoth
textLayer.add(keyframeAnimation, forKey: "hidden")
CABasicAnimation *endAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
endAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[endAnimation setFromValue:[NSNumber numberWithFloat:1]];
[endAnimation setToValue:[NSNumber numberWithFloat:0.0]];
[endAnimation setBeginTime:AVCoreAnimationBeginTimeAtZero];
endAnimation.duration = 5;
endAnimation.removedOnCompletion = NO;
[alayer addAnimation:endAnimation forKey:nil];