I'm trying execute a couple of animations at the same time. One is transitioning from one uimageview to another and the other is animating translation.x of a label. The label resides on top of uiimageview.
But what I get is either translation working fine and transition happens immediately, or the transitioning -based on hidden property - also applies to my label which should only be shifted (it also goes from hidden to visible). I can't use caanimationgroup because they apply to different views.
//CAKeyFrameAnimation for sliding the label
...
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:#"transform.translation.x"];
NSArray *xValues = #[[NSNumber numberWithFloat:myLabel.bounds.origin.x],
[NSNumber numberWithFloat:myLabel.bounds.origin.x + screenHalf],
[NSNumber numberWithFloat:myLabel.bounds.origin.x + screenHalf * 4]];
[anim setValues:xValues];
NSMutableArray *timeFrames = [NSMutableArray array];
CGFloat timeStep = 1.0 / ([xValues count] - 1);
for (NSInteger i = 0; i < [xValues count]; i++)
{
[timeFrames addObject:[NSNumber numberWithFloat:timeStep * i]];
}
[anim setKeyTimes:timeFrames];
[anim setDuration:duration];
[anim setFillMode:kCAFillModeForwards];
[anim setRemovedOnCompletion:FALSE];
[myLabel.layer addAnimation:anim forKey:nil];
...
//Transitioning from uiimageview to another one
...
CATransition *transition = [CATransition animation];
[transition setDuration:duration];
[transition setType:kCATransitionFade];
//These two are uiimageviews i'm switching from and to
initial.hidden = TRUE;
next.hidden = FALSE;
//Initial and next are subviews of container which itself is a subview of viewcontroller's main view
[container.layer addAnimation:transition forKey:#""];
If I call the animations like above the transition occurs immediately and label slides across screen correctly. If I change the last line to:
[self.view.layer addAnimation:transition forKey:#""];
Then hidden animation also applies to myLabel. What is the fix for combining animations like above, and also more elaborately what is the cause?
I would wrap the entire code in a CATransaction to group the different CAAnimations into a single group.
Psuedo-code for using this with CAKeyFrameAnimation would look like:
[CATransaction begin];
// set completion block if you want
[CATransaction setCompletionBlock:^{ NSLog(#"I'm done"); }];
// start a keyframe animation
CAKeyframeAnimation *key1 = .....
// start another keyframe animation block
CAKeyframeAnimation *key2 = ......
// Maybe do a basic animation
CABasicAnimation *anim1 = .....
// close out all the animations and have them start
[CATransaction commit];
Related
In this code i am using animation.But at a time i need to change the image alpha value also.
-(void)animation
{
CGPoint point = CGPointMake(imgView.frame.origin.x, imgView.frame.origin.y);
imgView.layer.position = point;
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"position.x"];
anim.fromValue = [NSValue valueWithCGPoint:point];
anim.toValue = [NSValue valueWithCGPoint:CGPointMake(point.x + 50, point.y)];
anim.duration = 10.0f;
anim.repeatCount =1;
anim.removedOnCompletion = YES;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[imgView.layer addAnimation:anim forKey:#"position.x"];
imgView.layer.position = point;
}
You can use the opacity key of CABasicAnimation for doing this:
CABasicAnimation *alphaAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
alphaAnimation.fromValue = [NSNumber numberWithFloat:1.0];
alphaAnimation.toValue = [NSNumber numberWithFloat:0.0];
[imgView.layer addAnimation:alphaAnimation forKey:#"opacity"];
Edit:
For animating through specified values you can use CAKeyframeAnimation:
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:#"opacity"];
animation.duration = 10.0f;
animation.repeatCount = 1;
animation.values = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:1.0,
[NSNumber numberWithFloat:0.5],
[NSNumber numberWithFloat:1.0],nil];
animation.keyTimes = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0],
[NSNumber numberWithFloat:5.0],
[NSNumber numberWithFloat:10.0], nil];
[imgView.layer addAnimation:animation forKey:#"opacity"];
In order to decrease the alpha as the same time/rate the x position of your view is moving, just put the position setting code together with the alpha setting code in the same block of animation, like below:
CGPoint finalPoint = CGPointMake(500, imgView.center.y); //change for any final point you want
CGFloat finalAlpha = 0.0; //change the final alpha as you want
UIView animateWithDuration:1.0 animations:^{ //change the duration as you want
imgView.alpha = finalAlpha;
imgView.center = finalPoint;
}];
This "fades to invisible" self.view in 500ms.
Anything you do prior to invoking it will be set "immediately", everything you set within the `animation' block (like setting new frame coordinates) will be interpolated over the specified duration.
[UIView animateWithDuration:0.50
delay:0.0
options:( UIViewAnimationOptionAllowUserInteraction
| UIViewAnimationOptionBeginFromCurrentState
| UIViewAnimationOptionCurveEaseInOut)
animations:^ {
self.view.alpha = 0.0f ;
}
completion: ^(BOOL){
[self.view removeFromSuperview] ;
self.view = nil ;
}
] ;
You may use a CABasicAnimation object (a different one because you will animate a different KeyPath, namely alpha, for this) and use NSNumbers for fromValue and toValue.
Another (and easiest) way is to use the UIView helper methods dedicated to animation ( animateWithDuration:… and all), especially if you have to animate multiple properties at the same time (you may animate both the frame and the alpha with the same animation block if it fits your needs and simplify your code).
You can also mix CABasicAnimation for the frame and [UIView animateWithDuration:…] for the alpha, whatever combination you need depending on if your animations are complex and need to be customized (custom timing function, non-linear animation, …) or not.
//your code of changing x position will be here
now implement my code which is written below.
UIView animateWithDuration:1.0 animations:^{
imgView.alpha = 0.5;//must be in between 0 to 1
}];
now when your imageview move to next position as you are saying, write below code
//your code for imageview for next position..
now implement below code...
UIView animateWithDuration:0.5 animations:^{
imgView.alpha = 1.0;//must be in between 0 to 1
}];
let me know it is working or not!!!! Hope it helps...
Happy Coding!!!
I have 3 animations running in a group: position, scale and rotation
However my rotation animation does not happen smoothly. It happens abruptly in the beginning, while other animations happen smoothly.
Here is my code:
//CABasicAnimation *scaleAnimation
//CABasicAnimation *moveAnimation
CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.y"];
rotationAnimation.autoreverses = NO;
rotationAnimation.toValue = [NSNumber numberWithFloat: 0];//-(M_PI/3)];
//below line shows the end state, if removed, the layer will assume its initial position after animation, something which I don't want.
[layer setTransform:CATransform3DMakeRotation(0, 0, 1, 0)];
CAAnimationGroup *theGroup = [CAAnimationGroup animation];
//Code for adding all 3 animations to the group
Edit:
rotationAnimation.toValue = [NSNumber numberWithFloat: -(M_PI/3)];
Removed final transform value from the place of animation declaration, and added it to delegate. (note that in case of animation group, individual animation delegates do not get hit, only the group delegate worked).
Under delegate:
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
NSString * animName = [theAnimation valueForKey:#"animationName"];
CALayer* layer = [theAnimation valueForKey:#"animationLayer"];
if ([animName isEqualToString:#"MoveZoomOut"])
{
if ([layer.name isEqualToString:#"Layer1"])
[layer setTransform:CATransform3DMakeRotation(-M_PI/3, 0, 1, 0)];
else if ([layer.name isEqualToString:#"Layer2"])
[layer setTransform:CATransform3DMakeRotation(M_PI/3, 0, 1, 0)];
else
[layer setTransform:CATransform3DMakeRotation(0, 0, 1, 0)];
}
if ([layer respondsToSelector:#selector(setContentsScale:)])
{
layer.contentsScale = [UIScreen mainScreen].scale;
}
}
I have 3 animations running in a group: position, scale and rotation
I suspect that since you are animating both scale and rotation, which is done through the transform property, there might be a clash.
Try to animate scale and rotation in a single animation by concatenating the 2 transforms into one:
CATransform3D t = CATransform3DMakeRotation(0, 0, 1, 0)];
[layer setTransform:CATransform3DScale(t, sx, sy, sz)];
EDIT:
I understand that what is happening is pretty unusual, so I will give you a couple of hints as to tricks that in several occasions helped me. I understand, you have 3 layers to animate.
wrap each layer animations in [CATransaction begin]/[CATransaction commit];
if that does not help,
do not set the final value of the property you are going to animate right after creating the animation itself; rather set it in the animation delegate animationDidStop:finished: method.
In other words, given your code:
CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.y"];
rotationAnimation.autoreverses = NO;
rotationAnimation.toValue = [NSNumber numberWithFloat: 0];//-(M_PI/3)];
//below line shows the end state, if removed, the layer will assume its initial position after animation, something which I don't want.
[layer setTransform:CATransform3DMakeRotation(0, 0, 1, 0)];
CAAnimationGroup *theGroup = [CAAnimationGroup animation];
don't do [layer setTransform:CATransform3DMakeRotation(0, 0, 1, 0)]; there. Rather, do it in:
- (void)animationDidStop:(CAAnimation*)anim finished:(BOOL)flag {
[layer setTransform:CATransform3DMakeRotation(0, 0, 1, 0)];
}
Since you will have more than one animation going on (and presumably use the same delegate for all of them), you will need a way to tell which animation the animationDidStop: method refers to. To this aim, you could do, e.g.:
//-- se the delegate
rotationAnimation.delegate = self;
[rotationAnimation setValue:layer forKey:#"animationLayer"];
and in the delegate method:
- (void)animationDidStop:(CAAnimation*)anim finished:(BOOL)flag {
[CATransaction begin];
[CATransaction setDisableActions:YES];
CALayer* layer = [anim valueForKey:#"animationLayer"];
layer.transform = ...;
[CATransaction commit];
}
I know that this seems a bit contrived. And it is. But it is the only way I could fix an issue similar to what you are reporting.
Hope this helps.
EDIT:
For the glitch when using animationDidStop:, try to wrap animationDidStop: content in:
[CATransaction begin];
[CATransaction setDisableActions:YES];
...
[CATransaction commit];
I want to crossfade between two different UIImages but for a reason i cannot figure out my first UIImage stays when the second one fades in.
Here is the sourcecode of my animation (it does a lot more than just crossfading, but the crossfading is my only problem right now).
I need all of the three animations listed below to be executed at the same time.
CGMutablePathRef thePath = CGPathCreateMutable();
CGPathMoveToPoint(thePath,NULL,startPoint.x, startPoint.y);
CGPathAddLineToPoint(thePath, NULL, endPoint.x, endPoint.y);
CAKeyframeAnimation *positionAnimation =[CAKeyframeAnimation animationWithKeyPath:#"position"];
positionAnimation.path=thePath;
positionAnimation.duration=ti_duration;
positionAnimation.repeatCount=0;
positionAnimation.delegate = self;
positionAnimation.autoreverses=NO;
positionAnimation.fillMode=kCAFillModeForwards;
positionAnimation.removedOnCompletion = NO;
[self.layer addAnimation:positionAnimation forKey:s_direction];
CABasicAnimation *crossFade = [CABasicAnimation animationWithKeyPath:#"contents"];
crossFade.duration = ti_duration;
crossFade.fromValue = (id)img_startImage.CGImage;
crossFade.toValue = (id)img_transferImage.CGImage;
[self.iv_image.layer addAnimation:crossFade forKey:#"animateContentsToTransferState"];
[self.iv_image setImage:img_transferImage];
CAAnimationGroup *theGroup = [CAAnimationGroup animation];
theGroup.duration = ti_duration;
theGroup.repeatCount = 0;
theGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
theGroup.animations = [NSArray arrayWithObjects:/*positionAnimation,*/ crossFade, nil]; // you can add more
[self.layer addAnimation:theGroup forKey:#"move"];
[UIView beginAnimations:#"changeSize" context:nil];
[UIView setAnimationDuration:duration];
self.bounds = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.transferSize.width, self.transferSize.height);
[UIView commitAnimations];
The animation method containing this sourcecode is in a subclass of UIView. This subclass contains several UIImages and one UIImageView where the image to be displayed is contained in.
Have i forgotten some essential thing or why is my first image not fading away?
Can it be because it is animated from some other animation at the same time?
I hope someone can help me with this.
Greets
Maverick
Think of CAAnimations as operations applied to the CALayer. The animations current state do not change the layers original contents.
When the original state seems to snap back at the end of the animation it is actually just the animations operation being removed, and the real layers state is being revealed again.
What you need to do is to register a delegate for your animation, and change the actual self.layer.contents when the animation ends.
First:
crossFade.delegate = self;
Then implement:
- (void)animationDidStop:(CABasicAnimation *)animation finished:(BOOL)flag {
self.layer.contents = animation.toValue;
}
Try this code...It worked for me.
-(void)crossFadeImage{
CABasicAnimation *crossFade = [CABasicAnimation animationWithKeyPath:#"contents"];
crossFade.duration = 2.0;
crossFade.fromValue = img1.CGImage;
crossFade.toValue = img2.CGImage;
[self.background.layer addAnimation:crossFade forKey:#"animateContents"];
self.background.image = img2;
}
I am taking the "Flipped Text" imageView and rotating it while moving it downwards on the screen and adjusting the frame. I am also swapping out the image for a different, but similar image.
Everything works as indicated except for the image crossfade is still showing the original position for the fade-out instead of following the movement. This screenshot shows the original, transition and end states for the animation, and clearly shows the problem.
My code looks like this (logoImage is a UIImageView):
// Swap it
self.logoImage.image = [UIImage imageNamed:#"logo.png"];
CATransition *transition = [CATransition animation];
transition.duration = duration;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;
[self.logoImage.layer addAnimation:transition forKey:nil];
// Spin it
CABasicAnimation* spinAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
spinAnimation.toValue = [NSNumber numberWithFloat:6*M_PI];
spinAnimation.duration = duration;
spinAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
spinAnimation.removedOnCompletion = YES;
spinAnimation.fillMode = kCAFillModeForwards;
[self.logoImage.layer addAnimation:spinAnimation forKey:#"spinAnimation"];
// Shrink it and Move it
CGRect newFrame = [self logoFrameForInterfaceOrientation:self.interfaceOrientation];
[UIView animateWithDuration:duration
delay:0.0
options:UIViewAnimationCurveEaseOut
animations:^{
self.logoImage.frame = newFrame;
}
completion:nil];
How can I make the crossfade of the image swap happen in place?
Try swapping the image in the completion block. (currently nil)
edit:
If they are substantially different, you can use a second UIImageView. Fade one out while you fade one in. You can either do this while they are translating, or wait for the "shrunken" original to arrive and fade it out while the "better" smaller version fades in.
Then remove the unneeded extra view in the completion block of that animation.
i want to replicate the animation when an app starts on iPhone.
There is the first view scaling up from 50 % to 100% i think.
later I want to use this as a transition between 2 views.
Any ideas how to replicate, or is there a ready to use solution from apple in the sdk?
Thank you very much :)
You can do the same thing with CABasicAnimation and CAAnimationGroup, I actually thought that Core Animation over UIKit Animations was smoother and It gives you more control.
CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
animationGroup.removedOnCompletion = YES;
CABasicAnimation *fadeAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
fadeAnimation.fromValue = [NSNumber numberWithFloat:0.0];
fadeAnimation.toValue = [NSNumber numberWithFloat:1.0];
CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:#"transform.scale"];
scaleAnimation.fromValue = [NSNumber numberWithFloat:0.5];
scaleAnimation.toValue = [NSNumber numberWithFloat:1.00];
animationGroup.animations = [NSArray arrayWithObjects:fadeAnimation, scaleAnimation, nil];
[self.layer addAnimation:animationGroup forKey:#"fadeAnimation"];
self.layer.opacity = 1.0;
"There's always more then one way to skin a cat"
You can apply a scale transform to the UIView and then animate it back to it's normal state.
// Set the the view's scale to half
[viewToScale setTransform:CGAffineTransformMakeScale(0.5,0.5)];
// Set the transform back to normal (identity) in an animation when you're
// ready to animate
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
[viewToScale setTransform:CGAffineTransformIdentity];
[UIView commitAnimations];
The trick will be you will need to set the view to the smaller scale in a separate run cycle from the animation or you won't see the view animate. So you can set the smaller scale and then call -performSelector:withObject:afterDelay: to actually perform the animation.