CALayer setPosition not called during animation - ios

I have a custom CALayer that I am animating using a CAAnimationGroup to follow a path and rotate at a tangent to the path:
// Create the animation path
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;
//Setting Endpoint of the animation
CGRect contentBounds = [self contentBounds];
self.boatLayer.bounds = contentBounds;
CGPoint endPoint = CGPointMake(contentBounds.size.width - 150, contentBounds.size.height - 150);
CGMutablePathRef curvedPath = CGPathCreateMutable();
CGPathMoveToPoint(curvedPath, NULL, startPosition.x, startPosition.y);
CGPathAddCurveToPoint(curvedPath, NULL, endPoint.x, 0, endPoint.x, 0, endPoint.x, endPoint.y);
pathAnimation.path = curvedPath;
pathAnimation.duration = 10.0;
pathAnimation.rotationMode = kCAAnimationRotateAuto;
pathAnimation.delegate = self;
// Create an animation group of all the animations
CAAnimationGroup *animationGroup = [[[CAAnimationGroup alloc] init] autorelease];
animationGroup.animations = [NSArray arrayWithObjects:pathAnimation, nil];
animationGroup.duration = 10.0;
animationGroup.removedOnCompletion = NO;
// Add the animations group to the layer (this starts the animation at the next refresh cycle)
[testLayer addAnimation:animationGroup forKey:#"animation"];
I need to be able to track the changes to the position and rotation of the layer as it progresses along the path. I have overridden both setPosition and setTransform (calling super setPosition and super setTranform) and then logging their values. Neither of these values appear to be set during the animation.
How can I get the position and rotation updates from within the CALayer class itself as it animates?

Core Animation doesn't work like that
Sorry. That is not how Core Animation work. When you add an animation to a layer it doesn't change the model of that layer. Only the presentation.
When you configure then animation to not remove itself upon completion
yourAnimation.fillMode = kCAFillModeForwards;
tourAnimation.removedOnCompletion = NO;
you are actually causing an inconsistency between what is shown on screen and the model of that layer. If you for instance had a button that you animated like this you would get very surprised/angry by the fact that it "no longer responds to toucher" or even more funny "responds to touches from it's 'old' location".
Semi-solutions
Depending on what and how often you actually need the updates you could either periodically check the value of the presentationLayer during the animation or use a CADisplayLink to run some code when the screen changes.

Related

IOS current keyframe y axis

Hey im trying to show the y axis of my imageview while its moving , but its not displaying the animating y axis , its showing only one number .
//LINE ANAMATION
CALayer *layer = line.layer;
CGPoint startPoint = (CGPoint){line.center.x,20};
CGPoint endPoint = (CGPoint){line.center.x, screenSizeY/2};
CGMutablePathRef thePath = CGPathCreateMutable();
CGPathMoveToPoint(thePath, NULL, startPoint.x, startPoint.y);
CGPathAddLineToPoint(thePath, NULL, endPoint.x, endPoint.y);
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
animation.duration = 3.f;
animation.path = thePath;
animation.autoreverses = YES;
animation.repeatCount = INFINITY;
[layer addAnimation:animation forKey:#"position"];
NSLog(#"%f", line.center.y);
There are a couple of things wrong with this. First, the animation state is maintained in the presentation layer. Your view and underlying layer are will reflect the final state of the animation immediately. Second, your NSLog statement will only be called once because you aren't in a loop.
If you want to do something at each frame of an animation, you can use CADisplayLink to get a callback on each frame. In this callback, you can check the current Y position by looking at the presentation layer:
- (void)myCallback:(CADisplayLink *)link
{
NSLog(#"%f", CGRectGetMidY(line.layer.presentationLayer.frame));
}

Animation similar to iPhone Camera App where the captured image drops into the picture viewer

I'm working on a iOS camera app, and want to create an animation similar to what the default camera app does on capturing an image (not the shutter animation). The captured image seems to drop into the photo viewer located at the bottom left corner of the screen. Any ideas on how to achieve this? I have not tried animating view controllers before, so I'm a bit lost on how to do it.
* EDIT Implementation issues *
So I've learned how to do the animation, and the animation seems to work fine with a test Image but when I use the actual image returned from the AVCapture connection, the animation goes haywire. The image looks distorted (something wrong with the aspect ratio) and the path it follows is opposite to the actual one. This is the code I'm using to animate:
- (void)animateImage:(UIImage*) image {
UIImageView *animator = [[UIImageView alloc]initWithImage:image];
animator.frame = previewView.frame;
animator.contentMode = UIViewContentModeScaleAspectFit;
[self.previewView addSubview:animator];
[CATransaction begin]; {
[CATransaction setCompletionBlock:^{
[animator removeFromSuperview];
}];
// Set up scaling
CABasicAnimation *resizeAnimation = [CABasicAnimation animationWithKeyPath:#"bounds"];
// Set to value to (0,0) rectangle
[resizeAnimation setToValue:[NSValue valueWithCGSize:CGSizeMake(0,0)]];
resizeAnimation.fillMode = kCAFillModeForwards;
resizeAnimation.removedOnCompletion = NO;
// Set up path movement
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;
//Setting Endpoint of the animation
CGPoint endPoint = CGPointMake( animator.frame.size.width, animator.frame.size.height);
CGMutablePathRef curvedPath = CGPathCreateMutable();
CGPathMoveToPoint(curvedPath, NULL, 0, 0);
// CGPathMoveToPoint(curvedPath, NULL, animator.frame.size.width/2, animator.frame.size.height/2);
// CGPathAddCurveToPoint(curvedPath, NULL, 0,0,0,0, endPoint.x, endPoint.y);
CGPathAddLineToPoint(curvedPath, NULL, endPoint.x, endPoint.y);
pathAnimation.path = curvedPath;
CGPathRelease(curvedPath);
CAAnimationGroup *group = [CAAnimationGroup animation];
// group.fillMode = kCAFillModeForwards; // keep the final value after completion of animation
// group.removedOnCompletion = NO; // "
[group setAnimations:[NSArray arrayWithObjects: pathAnimation, resizeAnimation, nil]];
group.duration = 3.0f;
group.delegate = self;
[group setValue:animator forKey:#"imageViewBeingAnimated"];
[animator.layer addAnimation:group forKey:#"cameraAnimation"];
} [CATransaction commit];
}
It seems to work when I take the picture in landscape mode, but not in Portrait . It's something to do with orientation, but I cant figure out what could be wrong..
"previewView" frame is the AVCapture Preview Layer over which I add the UIImage and then scale and move it to a corner.
* Final EDIT *
Fixed using the transform property instead of bounds.size. Similar to the example here:
http://www.verious.com/article/animating-interfaces-with-core-animation-part-3/
Phew!
Really this is quite simple, after the photo is taken, stick the returned UIimage in a UIImageView and then use core animation blocks to resize and animate the frame whilst making the imageview follow a bezierpath down to the photo viewer in the botton left corner.
Let me know if you need any further help with these steps.

Group animation on multiple objects

I'm trying to animate many bubbles coming out of a machine. I'm using a basic animation to scale the bubbles from a small bubble to a large one and a keyframe animation to send the bubble in a curve across the screen. These are combined into a group animation.
I have read through just about all I can to try to get this to work, but I have the following two problems.
I can't get the scale animation to work together with the keyframe
animation when I try to animate each bubble.
The animation happens to them all at the same time. I'd like to see them animated one
after the other, but they all animate together.
here is the animation code I have.
-(void)EmitBubbles:(UIButton*)bubblename :(CGRect)RectPassed
{
bubblename.hidden = NO;
// Set position and size of each bubble to be at head of bubble machine and size (0,0)
CGPoint point = (RectPassed.origin);
CGRect ButtonFrame;
ButtonFrame = bubblename.bounds;
ButtonFrame.size = CGSizeMake(0, 0);
bubblename.bounds = ButtonFrame;
CGRect OldButtonBounds = bubblename.bounds;
CGRect NewButtonBounds = OldButtonBounds;
NewButtonBounds.size = RectPassed.size;
CGFloat animationDuration = 0.8f;
// Set up scaling
CABasicAnimation *resizeAnimation = [CABasicAnimation animationWithKeyPath:#"bounds.size"];
resizeAnimation.fillMode = kCAFillModeForwards;
resizeAnimation.duration = animationDuration;
resizeAnimation.fromValue = [NSValue valueWithCGSize:OldButtonBounds.size];
resizeAnimation.toValue = [NSValue valueWithCGSize:NewButtonBounds.size];
// Set Actual bubble size after animation
bubblename.bounds = NewButtonBounds;
// Setup Path
CGPoint MidPoint = CGPointMake(500,50);
CGPoint EndPoint = CGPointMake(RectPassed.origin.x, RectPassed.origin.y);
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
CGMutablePathRef curvedPath = CGPathCreateMutable();
CGPathMoveToPoint(curvedPath, nil, bubblename.bounds.origin.x, bubblename.bounds.origin.y);
CGPoint NewLoc = CGPointMake(745, 200);
CGPathMoveToPoint(curvedPath, NULL, NewLoc.x,NewLoc.y);
CGPathAddCurveToPoint(curvedPath, NULL, 745,200,MidPoint.x,MidPoint.y, EndPoint.x, EndPoint.y);
pathAnimation.path = curvedPath;
// Set Bubble action position after animation
bubblename.layer.position = point;
// Add scale and path to animation group
CAAnimationGroup *group = [CAAnimationGroup animation];
group.removedOnCompletion = YES;
[group setAnimations:[NSArray arrayWithObjects:pathAnimation, resizeAnimation, nil]];
group.duration = animationDuration;
[bubblename.layer addAnimation:group forKey:#"nil"]; //savingAnimation
CGPathRelease(curvedPath);
}
I call the animation for each bubble using
[self EmitBubbles:btnbubble1 :CGRectMake(200, 500, 84, 88)];
[self EmitBubbles:btnbubble2 :CGRectMake(200, 500, 84, 88)];
I have 20 bubbles on screen. The size of the rect passed is the final size I want the bubbles to be.
Can I can get each bubble to animate separately using a scale and keyframe path, without having to write the above code for each bubble?
Thanks
OK. I think I did it.After hours of looking around Stackoverflow and other places I found that to bhave the objects animate one after the other. I had to calculate the time according to the app time. I used.
group.beginTime = CACurrentMediaTime() + AnimationDelay
To stop the animation momentarily appearing at its final position before continuing with the animation. I had to use
group.fillMode = kCAFillModeBackwards;

Cannot get current position of CALayer during animation

I am trying to achieve an animation that when you hold down a button it animates a block down, and when you release, it animates it back up to the original position, but I cannot obtain the current position of the animating block no matter what. Here is my code:
-(IBAction)moveDown:(id)sender{
CGRect position = [[container.layer presentationLayer] frame];
[movePath moveToPoint:CGPointMake(container.frame.origin.x, position.y)];
[movePath addLineToPoint:CGPointMake(container.frame.origin.x, 310)];
CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
moveAnim.path = movePath.CGPath;
moveAnim.removedOnCompletion = NO;
moveAnim.fillMode = kCAFillModeForwards;
CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations = [NSArray arrayWithObjects:moveAnim, nil];
animGroup.duration = 2.0;
animGroup.removedOnCompletion = NO;
animGroup.fillMode = kCAFillModeForwards;
[container.layer addAnimation:animGroup forKey:nil];
}
-(IBAction)moveUp:(id)sender{
CGRect position = [[container.layer presentationLayer] frame];
UIBezierPath *movePath = [UIBezierPath bezierPath];
[movePath moveToPoint:CGPointMake(container.frame.origin.x, position.y)];
[movePath addLineToPoint:CGPointMake(container.frame.origin.x, 115)];
CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
moveAnim.path = movePath.CGPath;
moveAnim.removedOnCompletion = NO;
moveAnim.fillMode = kCAFillModeForwards;
CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations = [NSArray arrayWithObjects:moveAnim, nil];
animGroup.duration = 2.0;
animGroup.removedOnCompletion = NO;
animGroup.fillMode = kCAFillModeForwards;
[container.layer addAnimation:animGroup forKey:nil];
}
But the line
CGRect position = [[container.layer presentationLayer] frame];
is only returning the destination position not the current position. I need to basically give me the current position of the container thats animating once I release the button, so I can perform the next animation. What I have now does not work.
I haven't analyzed your code enough to be 100% sure why [[container.layer presentationLayer] frame] might not return what you expect. But I see several problems.
One obvious problem is that moveDown: doesn't declare movePath. If movePath is an instance variable, you probably want to clear it or create a new instance each time moveDown: is called, but I don't see you doing that.
A less obvious problem is that (judging from your use of removedOnCompletion and fillMode, in spite of your use of presentationLayer) you apparently don't understand how Core Animation works. This turns out to be surprisingly common, so forgive me if I'm wrong. Anyway, read on, because I will explain how Core Animation works and then how to fix your problem.
In Core Animation, the layer object you normally work with is a model layer. When you attach an animation to a layer, Core Animation creates a copy of the model layer, called the presentation layer, and the animation changes the properties of the presentation layer over time. An animation never changes the properties of the model layer.
When the animation ends, and (by default) is removed, the presentation layer is destroyed and the values of the model layer's properties take effect again. So the layer on screen appears to “snap back” to its original position/color/whatever.
A common, but wrong way to fix this is to set the animation's removedOnCompletion to NO and its fillMode to kCAFillModeForwards. When you do this, the presentation layer hangs around, so there's no “snap back” on screen. The problem is that now you have the presentation layer hanging around with different values than the model layer. If you ask the model layer (or the view that owns it) for the value of the animated property, you'll get a value that's different than what's on screen. And if you try to animate the property again, the animation will probably start from the wrong place.
To animate a layer property and make it “stick”, you need to change the model layer's property value, and then apply the animation. That way, when the animation is removed, and the presentation layer goes away, the layer on screen will look exactly the same, because the model layer has the same property values as its presentation layer had when the animation ended.
Now, I don't know why you're using a keyframe to animate straight-line motion, or why you're using an animation group. Neither seems necessary here. And your two methods are virtually identical, so let's factor out the common code:
- (void)animateLayer:(CALayer *)layer toY:(CGFloat)y {
CGPoint fromValue = [layer.presentationLayer position];
CGPoint toValue = CGPointMake(fromValue.x, y);
layer.position = toValue;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"position"];
animation.fromValue = [NSValue valueWithCGPoint:fromValue];
animation.toValue = [NSValue valueWithCGPoint:toValue];
animation.duration = 2;
[layer addAnimation:animation forKey:animation.keyPath];
}
Notice that we're giving the animation a key when I add it to the layer. Since we use the same key every time, each new animation will replace (remove) the prior animation if the prior animation hasn't finished yet.
Of course, as soon as you play with this, you'll find that if you moveUp: when the moveDown: is only half finished, the moveUp: animation will appear to be at half speed because it still has a duration of 2 seconds but only half as far to travel. We should really compute the duration based on the distance to be travelled:
- (void)animateLayer:(CALayer *)layer toY:(CGFloat)y withBaseY:(CGFloat)baseY {
CGPoint fromValue = [layer.presentationLayer position];
CGPoint toValue = CGPointMake(fromValue.x, y);
layer.position = toValue;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"position"];
animation.fromValue = [NSValue valueWithCGPoint:fromValue];
animation.toValue = [NSValue valueWithCGPoint:toValue];
animation.duration = 2.0 * (toValue.y - fromValue.y) / (y - baseY);
[layer addAnimation:animation forKey:animation.keyPath];
}
If you really need it to be a keypath animation in an animation group, your question should show us why you need those things. Anyway, it works with those things too:
- (void)animateLayer:(CALayer *)layer toY:(CGFloat)y withBaseY:(CGFloat)baseY {
CGPoint fromValue = [layer.presentationLayer position];
CGPoint toValue = CGPointMake(fromValue.x, y);
layer.position = toValue;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:fromValue];
[path addLineToPoint:toValue];
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
animation.path = path.CGPath;
animation.duration = 2.0 * (toValue.y - fromValue.y) / (y - baseY);
CAAnimationGroup *group = [CAAnimationGroup animation];
group.duration = animation.duration;
group.animations = #[animation];
[layer addAnimation:group forKey:animation.keyPath];
}
You can find the full code for my test program in this gist. Just create a new Single View Application project and replace the contents of ViewController.m with the contents of the gist.

iOS CAKeyFrameAnimation Scaling Flickers at animation end

In another test of Key Frame animation I am combining moving a UIImageView (called theImage) along a bezier path and scaling larger it as it moves, resulting in a 2x larger image at the end of the path. My initial code to do this has these elements in it to kick off the animation:
UIImageView* theImage = ....
float scaleFactor = 2.0;
....
theImage.center = destination;
theImage.transform = CGAffineTransformMakeScale(1.0,1.0);
CABasicAnimation *resizeAnimation = [CABasicAnimation animationWithKeyPath:#"bounds.size"];
[resizeAnimation setToValue:[NSValue valueWithCGSize:CGSizeMake(theImage.image.size.height*scaleFactor, theImage.image.size.width*scaleFactor)]];
resizeAnimation.fillMode = kCAFillModeBackwards;
resizeAnimation.removedOnCompletion = NO;
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.path = [jdPath path].CGPath;
pathAnimation.fillMode = kCAFillModeBackwards;
pathAnimation.removedOnCompletion = NO;
CAAnimationGroup* group = [CAAnimationGroup animation];
group.animations = [NSArray arrayWithObjects:pathAnimation, resizeAnimation, nil];
group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
group.removedOnCompletion = NO;
group.duration = duration;
group.delegate = self;
[theImage.layer addAnimation:group forKey:#"animateImage"];
Then, when the animation completes I want to retain the image at the larger size, so I implement:
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
theImage.transform = CGAffineTransformMakeScale(scaleFactor,scaleFactor);
}
This all works .. sort of. The problem is that at the end of the animation theImage flickers for a brief moment - just enough to make it look bad. I am guessing that this is the transition at the end of the animation where I set the transform to the new size.
In experimenting with this I tried a slightly different form of the above, but still got the same flicker:
CAKeyframeAnimation *resizeAnimation = [CAKeyframeAnimation animationWithKeyPath:#"transform"];
NSValue* startSizeKey = [NSValue valueWithCATransform3D:CATransform3DScale (theImage.layer.transform, 1.0, 1.0, 1.0)];
NSValue* endSizeKey = [NSValue valueWithCATransform3D:CATransform3DScale (theImage.layer.transform, scaleFactor, scaleFactor, 1.0)];
NSArray* sizeKeys = [NSArray arrayWithObjects:startSizeKey, endSizeKey, nil];
[resizeAnimation setValues:sizeKeys];
....
theImage.transform = CGAffineTransformMakeScale(scaleFactor,scaleFactor);
But when I ended the animation at the same size as the original, there was NO flicker:
CAKeyframeAnimation *resizeAnimation = [CAKeyframeAnimation animationWithKeyPath:#"transform"];
NSValue* startSizeKey = [NSValue valueWithCATransform3D:CATransform3DScale (theImage.layer.transform, 1.0, 1.0, 1.0)];
NSValue* middleSizeKey = [NSValue valueWithCATransform3D:CATransform3DScale (theImage.layer.transform, scaleFactor, scaleFactor, 1.0)];
NSValue* endSizeKey = [NSValue valueWithCATransform3D:CATransform3DScale (theImage.layer.transform, 1.0, 1.0, 1.0)];
NSArray* sizeKeys = [NSArray arrayWithObjects:startSizeKey, middleSizeKey, endSizeKey, nil];
[resizeAnimation setValues:sizeKeys];
....
theImage.transform = CGAffineTransformMakeScale(1.0,1.0);
So my big question is how can I animate this image without the flicker, and end up with a different size at the end of the animation?
Edit March 2nd
My initial tests were with scaling the image up. I just tried scaling it down (IE scaleFactor = 0.4) and the flickering was a lot more visible, and a lot more obvious as to what I am seeing. This was the sequence of events:
Original sized image is painted on the screen at the starting location.
As the image moves along the path it shrinks smoothly.
The fully shrunk image arrives at the end of the path.
The image is then painted at its original size.
The image is finally painted at its shrunken size.
So it seems to be step 4 that is the flickering that I am seeing.
Edit March 22
I have just uploaded to GitHub a demo project that shows off the moving of an object along a bezier path. The code can be found at PathMove
I also wrote about it in my blog at Moving objects along a bezier path in iOS
It can be tricky to animate a view's layer using Core Animation. There are several things that make it confusing:
Setting an animation on a layer doesn't change the layer's properties. Instead, it changes the properties of a “presentation layer” that replaces the original “model layer” on the screen as long as the animation is applied.
Changing a layer's property normally adds an implicit animation to the layer, with the property name as the animation's key. So if you want to explicitly animate a property, you usually want to set the property to its final value, then add an animation whose key is the property name, to override the implicit animation.
A view normally disables implicit animations on its layer. It also mucks around with its layer's properties in other somewhat mysterious ways.
Also, it's confusing that you animate the view's bounds to scale it up, but then switch to a scale transformation at the end.
I think the easiest way to do what you want is to use the UIView animation methods as much as possible, and only bring in Core Animation for the keyframe animation. You can add the keyframe animation to the view's layer after you've let UIView add its own animation, and your keyframe animation will override the animation added by UIView.
This worked for me:
- (IBAction)animate:(id)sender {
UIImageView* theImage = self.imageView;
CGFloat scaleFactor = 2;
NSTimeInterval duration = 1;
UIBezierPath *path = [self animationPathFromStartingPoint:theImage.center];
CGPoint destination = [path currentPoint];
[UIView animateWithDuration:duration animations:^{
// UIView will add animations for both of these changes.
theImage.transform = CGAffineTransformMakeScale(scaleFactor, scaleFactor);
theImage.center = destination;
// Prepare my own keypath animation for the layer position.
// The layer position is the same as the view center.
CAKeyframeAnimation *positionAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
positionAnimation.path = path.CGPath;
// Copy properties from UIView's animation.
CAAnimation *autoAnimation = [theImage.layer animationForKey:#"position"];
positionAnimation.duration = autoAnimation.duration;
positionAnimation.fillMode = autoAnimation.fillMode;
// Replace UIView's animation with my animation.
[theImage.layer addAnimation:positionAnimation forKey:positionAnimation.keyPath];
}];
}
CAAnimations will flicker at the end if the terminal state was assigned in such a way that it itself created an implicit animation. Keep in mind CAAnimations are temporary adjustments of an object properties for the purposes of visualizing transition. When the animation done, if the layer's state is still the original starting state, that is what is going to be displayed ever so temporarily until you set the final layer state, which you do in your animationDidStop: method.
Furthermore, your animation is adjusting the bounds.size property of your layer, so you should similarly set your final state rather than using the transform adjustment as your final state. You could also use the transform property as the animating property in the animation instead of bounds.size.
To remedy this, immediately after assigning the animation, change the layer's permeant state to your desired terminal state so that when the animation completes there will be no flicker, but do so in such a manner to no trigger an implicit animation before the animation begins. Specifically, in your case you should do this at the end of your animation set up:
UIImageView* theImage = ....
float scaleFactor = 2.0;
....
theImage.center = destination;
theImage.transform = CGAffineTransformMakeScale(1.0,1.0);
CGSize finalSize = CGSizeMake(theImage.image.size.height*scaleFactor, theImage.image.size.width*scaleFactor);
CABasicAnimation *resizeAnimation = [CABasicAnimation animationWithKeyPath:#"bounds.size"];
[resizeAnimation setToValue:[NSValue valueWithCGSize:finalSize]];
resizeAnimation.fillMode = kCAFillModeBackwards;
resizeAnimation.removedOnCompletion = NO;
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.path = [jdPath path].CGPath;
pathAnimation.fillMode = kCAFillModeBackwards;
pathAnimation.removedOnCompletion = NO;
CAAnimationGroup* group = [CAAnimationGroup animation];
group.animations = [NSArray arrayWithObjects:pathAnimation, resizeAnimation, nil];
group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
group.removedOnCompletion = NO;
group.duration = duration;
group.delegate = self;
[theImage.layer addAnimation:group forKey:#"animateImage"];
[CATransaction begin];
[CATransaction setDisableActions:YES];
theImage.bounds = CGRectMake( theImage.bounds.origin.x, theImage.bounds.origin.y, finalSize.width, finalSize.height );
[CATransaction commit];
and then remove the transform adjustment in your animationDidStop: method.
I was experimenting with some CAAnimations this week and was noticing that there was a flickering at the end of my animations. In particular, I would animation from a circle to a square, while changing the fillColor as well.
Each CAAnimation has a property called removedOnCompletion which defaults to YES. This means that the animation will disappear (i.e. transitions, scales, rotations, etc.) when the animation completes and you'll be left with the original layer.
Since you already have set your removedOnCompletion properties to NO, I would suggest trying to shift your execution of your animations to use CATransactions, instead of delegates and animationDidStop...
[CATransaction begin];
[CATransaction setDisableActions:YES];
[CATransaction setCompletionBlock: ^{ theImage.transform = ...}];
// ... CAAnimation Stuff ... //
[CATransaction commit];
You put the transaction's completion block call before you create your animations, as per:
http://zearfoss.wordpress.com/2011/02/24/core-animation-catransaction-protip/
The following is from one of my methods:
[CATransaction begin];
CABasicAnimation *animation = ...;
animation.fromValue = ...;
animation.toValue = ...;
[CATransaction setCompletionBlock:^ { self.shadowRadius = _shadowRadius; }];
[self addAnimation:animation forKey:#"animateShadowOpacity"];
[CATransaction commit];
And, I constructed this animation and it works fine for me with no glitches at the end:
The setup and trigger are custom methods I have in a window, and i trigger the animation on mousedown.
UIImageView *imgView;
UIBezierPath *animationPath;
-(void)setup {
canvas = (C4View *)self.view;
imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"img256.png"]];
imgView.frame = CGRectMake(0, 0, 128, 128);
imgView.center = CGPointMake(384, 128);
[canvas addSubview:imgView];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[UIImageView animateWithDuration:2.0f animations:^{
[CATransaction begin];
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.duration = 2.0f;
pathAnimation.calculationMode = kCAAnimationPaced;
animationPath = [UIBezierPath bezierPath];
[animationPath moveToPoint:imgView.center];
[animationPath addLineToPoint:CGPointMake(128, 512)];
[animationPath addLineToPoint:CGPointMake(384, 896)];
pathAnimation.path = animationPath.CGPath;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;
[imgView.layer addAnimation:pathAnimation forKey:#"animatePosition"];
[CATransaction commit];
CGFloat scaleFactor = 2.0f;
CGRect newFrame = imgView.frame;
newFrame.size.width *= scaleFactor;
newFrame.size.height *= scaleFactor;
newFrame.origin = CGPointMake(256, 0);
imgView.frame = newFrame;
imgView.transform = CGAffineTransformRotate(imgView.transform,90.0*M_PI/180);
}];
}

Resources