CALayer explicit animations not behaving properly - core-animation

Implicitly things behave fine. But when i try to use explicit animations to do multiple animations on a single layer (e.g. opacity and translation) I get odd results.
First of all, i tried using CATransaction. Then i switched to CAAnimationGroup. Both doesnt seem to get what i want.
What do I want?
All i want is for a layer to move from one point to another with an initial opacity and a target opacity. thats it!
What am i seeing?
Here is one example...
When performing a transaction begin/commit, the translation appears to be correct, but the opacity is not. My start opacity is 0, and the target opacity is 0.5.
However when i run the animations, it blends to 0.5, but then "snaps" to 1.0 (fully opaque).
I tried setting the removedOnCompletion to NO. but that didnt help either.
I think the bottom line is that i need to know the difference between an AnimationGroup and a Transaction.
Can anybody explain this, and possibly what im seeing regarding the oddness of my animations?
Thanks!

Ok, explicit animations arent working for me.
I tried creating a basic animation for opacity (of a layer). I placed this inside an animation group. When i execute, nothing happens. For simplicity i took out translation animations. This is only trying to do opacity animation.
CAAnimationGroup *group = [CAAnimationGroup animation];
CABasicAnimation *opacityAnimation;
opacityAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
opacityAnimation.fromValue = [NSNumber numberWithDouble:fromalpha];
opacityAnimation.toValue = [NSNumber numberWithDouble:toalpha];
opacityAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
opacityAnimation.delegate = self;
opacityAnimation.duration = 2.7;
opacityAnimation.removedOnCompletion = NO;
group.animations = [NSArray arrayWithObjects: opacityAnimation, nil];
[baseLayer addAnimation:group forKey:#"groupAnim"];

You have to set the layers opacity to the value after the animation in explicit animations.
layer.opacity=0.0f;

Related

Smooth Animation on CAKeyframeAnimation for CATransform3D animations

I've created my own transition animation between views. I animate two properties, the position and the transform, to provide a cube-like transition between views. The frame uses CABasicAnimation while the transform uses a "2-stage" CAKeyframeAnimation. Everything works fine except for one small detail I can't seem to figure out. In my transition I apply a CATransform3DScale on the middle key frame to create a zoom-in/zoom-out effect. That works fine except the animation looks slightly jerky. It's animating the between the key frames in a linear fashion, and I would like to smooth that out. Now CAKeyframeAnimation has a way to do that using calculationMode, but it doesn't seem to work for transforms. I've tried setting it to kCAAnimationCubic and kCAAnimationCubicPaced with no effect.
Here is the code that animates one view's transform (a similar block of code animates the other view):
CAKeyframeAnimation *aTransform = [CAKeyframeAnimation animationWithKeyPath:#"transform"];
CATransform3D transform1 = RotateOnX(toView, M_PI_4);
transform1 = CATransform3DScale(transform1, RotationalZoom, RotationalZoom, RotationalZoom);
[aTransform setValues:Array([NSValue valueWithCATransform3D:RotateOnX(toView, M_PI_2)],
[NSValue valueWithCATransform3D:transform1],
[NSValue valueWithCATransform3D:RotateOnX(toView, 0)])];
[toView.layer addAnimation:aTransform forKey:#"transform"];
Note: RotateOnX(UIView *, CGFloat) is a block that returns a transform for a view rotated on X by the desired Radians.
As you can see I only set a scaling transform on the middle key frame. Also, the rotation of the view is perfectly smooth, it's only the scaling that appears to 'jerk' as it changes direction.
Does anyone have any ideas on how to smooth out the scaling/zooming?
Try the timingFunctions property. Since you have 3 keyframes, you need 2 timing functions: one for the animation from keyframe 0 to keyframe 1, and another for the animation from keyframe 1 to keyframe 2.
aTransform.timingFunctions = [NSArray arrayWithObjects:
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInOut],
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInOut],
nil];

How do I achieve continuous rotation of an NSImage inside NSImageView?

FUTURE VIEWERS:
I have managed to finish this rotation animation and code with description can be found on tho question. NSImage rotation in NSView is not working
Before you proceed please up vote Duncan C 's answer. As I manage to achieve this rotation from his answer.
I have an image like this,
I want to keep rotating this sync icon, On a different thread. Now I tried using Quartz composer and add the animation to QCView but it is has very crazy effect and very slow too.
Question :
How do I rotate this image continuously with very less processing expense?
Effort
I read CoreAnimation, Quartz2D documentation but I failed to find the way to make it work. The only thing I know so far is, I have to use
CALayer
CAImageRef
AffineTransform
NSAnimationContext
Now, I am not expecting code, but an understanding with pseudo code will be great!
Getting an object to rotate more than 180 degrees is actually a little bit tricky. The problem is that you specify a transformation matrix for the ending rotation, and the system decides to rotate in the other direction.
What I've done is to create a CABasicAnimation of less than 180 degrees, set up to be additive , and with a repeat count. Each step in the animation animates the object more.
The following code is taken from an iOS application, but the technique is identical in Mac OS.
CABasicAnimation* rotate = [CABasicAnimation animationWithKeyPath: #"transform.rotation.z"];
rotate.removedOnCompletion = FALSE;
rotate.fillMode = kCAFillModeForwards;
//Do a series of 5 quarter turns for a total of a 1.25 turns
//(2PI is a full turn, so pi/2 is a quarter turn)
[rotate setToValue: [NSNumber numberWithFloat: -M_PI / 2]];
rotate.repeatCount = 11;
rotate.duration = duration/2;
rotate.beginTime = start;
rotate.cumulative = TRUE;
rotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
CAAnimation objects operate on layers, so for Mac OS, you'll need to set the "wants layer" property in interface builder, and then add the animation to your view's layer.
To make your view rotate forever, you'd set repeat count to some very large number like 1e100.
Once you've created your animation, you'd add it to your view's layer with code something like this:
[myView.layer addAnimation: rotate forKey: #"rotateAnimation"];
That's about all there is to it.
Update:
I've recently learned of another way to handle rotations of greater than 180 degrees, or continuous rotations.
There is a special object called a CAValueFunction that lets you apply a change to your layer's transform using an arbitrary value, including values that specify multiple full rotations.
You create a CABasicAnimation of your layer's transform property, but then instead of providing a transform, the value you supply is an NSNumber that gives the new rotation angle. If you provide a new angle like 20pi, your layer will rotate 10 full rotations (2pi/rotation). The code looks like this:
//Create a CABasicAnimation object to manage our rotation.
CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:#"transform"];
rotation.duration = 10.0;
CGFLOAT angle = 20*M_PI;
//Set the ending value of the rotation to the new angle.
rotation.toValue = #(angle);
//Have the rotation use linear timing.
rotation.timingFunction =
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
/*
This is the magic bit. We add a CAValueFunction that tells the CAAnimation we are
modifying the transform's rotation around the Z axis.
Without this, we would supply a transform as the fromValue and toValue, and
for rotations > a half-turn, we could not control the rotation direction.
By using a value function, we can specify arbitrary rotation amounts and
directions and even rotations greater than 360 degrees.
*/
rotation.valueFunction =
[CAValueFunction functionWithName: kCAValueFunctionRotateZ];
/*
Set the layer's transform to it's final state before submitting the animation, so
it is in it's final state once the animation completes.
*/
imageViewToAnimate.layer.transform =
CATransform3DRotate(imageViewToAnimate.layer.transform, angle, 0, 0, 1.0);
[imageViewToAnimate.layer addAnimation:rotation forKey:#"transform.rotation.z"];
(I Extracted the code above from a working example application, and took out some things that weren't directly related to the subject. You can see this code in use in the project KeyframeViewAnimations (link) on github. The code that does the rotation is in a method called `handleRotate'

CALayer fade from current value

My app uses CALayer to draw views. More precisely, it uses the drawLayer:inContext: method on a sublayer of a UIView's top layer. This is a nice way to get the 'implicit' animation of consecutive drawLayer:inContext: drawings to fade into each other over time. The fading animations happen fairly fast, maybe in 0.25 seconds, but to change its duration, simply implement another delegate method called actionForLayer:forKey:. In this perfectly working example implementation here the default duration is stretched to 2.0 seconds:
- (id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)event
{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:event];
animation.duration = 2.0;
return animation;
// or return nil for the default duration.
}
On to the issue at hand.
If you call [sublayer setNeedsDisplay] faster than the fades have time to complete, with each new fade you'll see a sudden jump. From the looks of it, the fade that's in progress is cancelled and it's final state is used as the starting point of the new fade. This might not be very surprising, but the visual result is rather unwanted.
Consider the scenario of a ten second fade from black to white, with another fade, to black, triggered five seconds after the start. The animation will start fading from black to white, but when it's at a 'half way gray' it jumps to full white before fading to black again.
Is there a way to prevent this from happening? Can I get the layer to fade from the gray back down to black? Is there a CALayer drawing equivalent of saying UIViewAnimationOptionBeginFromCurrentState (used in UIView animations)?
Cheers.
A layer's animation is only a visual representation of what the layer should look like as it animates. In CA when you animate from one state to another, the entire state of the layer changes immediately. A presentation layer is created and displays the animation, and when the animation completes the actual layer is left in place at the end.
So, my guess is that when you want to transition from one state to another, and the current animation hasn't completed yet, you have to capture the current state of the animation and then use this as the starting point for your next animation.
The problem lies in not being able to modify a layer's current animation.
In the following post I capture the current state of an animation, set that as the current state for the layer and use that as the beginning value from which to animate. The post applies this technique to the speed / duration of an animation, but can also be applied to your scenario.
https://stackoverflow.com/a/9544674/1218605
I'm a little stumped on this one too.
Did you forget to specify the fillMode kCAFillModeForwards. There's more info about that in the reference docs.
For example, I got this to work without any snapping, although I'm not changing the duration.
#implementation FadingLayer
- (void)fadeOut {
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"backgroundColor"];
animation.fillMode = kCAFillModeForwards;
animation.fromValue = (id)[UIColor redColor].CGColor;
animation.toValue = (id)[UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.0].CGColor;
animation.removedOnCompletion = FALSE;
animation.delegate = self;
[self addAnimation:animation
forKey:#"test"];
}
- (void)fadeIn {
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"backgroundColor"];
animation.fillMode = kCAFillModeForwards;
animation.fromValue = (id)[UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.0].CGColor;
animation.toValue = (id)[UIColor redColor].CGColor;
animation.removedOnCompletion = FALSE;
animation.delegate = self;
[self addAnimation:animation
forKey:#"test"];
}
#end
You'll probably want to animate a custom property however.
Hope this helps :/
I wanted to accomplish the same thing with a zoom animation of a layer tree. I have a zoom in/out key-equivalent where the user can zoom the layer tree accordingly. However, if the user presses the zoom key-equivalent in rapid succession, there would be a temporary snap-back to the values prior to the onset of the animation, since the previous animation hadn't yet completed.
At the end of the animation code, performing a sole [CATransaction commit] forced any pending transactions to be committed to the layer model before the start of the next animation, and solved the problem.
The documentation says:
+ commit
Commit all changes made during the current transaction.
Declaration
+ (void)commit
Special Considerations
Raises an exception if no current transaction exists.
However, testing this with many [CATransaction commit] messages in succession doesn't actually raise an exception. I've used this same technique to squelch warnings of the form:
CoreAnimation: warning, deleted thread with uncommitted
CATransaction;
in an NSOperation whose thread of execution finishes before layer animations do. It could be that Apple changed this behaviour in recent OS releases to a no-op (which would be much saner) if no current transaction exists, without updating the documentation.

How to animate and rotate an image?

Hi i am working on an iPhone application and i have to animate and rotate an image, Image is attached here
now purpose of this image is that whenever any tap some where on iPad it will animate and will point towards that place.
Please help me to figure it out. Thanx
Try this -
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
animation.fromValue = [NSNumber numberWithFloat:0.0f];
animation.toValue = [NSNumber numberWithFloat: 2*M_PI];
animation.duration = 10.0f;
animation.repeatCount = INFINITY;
[self.yourImage.layer addAnimation:animation forKey:#"SpinAnimation"];
check this tutorial. It will really help you.
To animate images view, you'll need to use CoreAnimation.
All you have to do is making UIImageView object with your image inside and then you'll manipulate directly the layer to animate.
There is 2 kind of animation with core animation :
Implicit animation (normally they are activate by default) : Everytime you change some setting on the layer (like position with [imageView.layer setPosition:CGPointMake...]) there should be an implicit animation with default parameters (Duration, AnimationCurve etc.)
Explicit animation : If you want to create more complex animations, you should use explicit animation, it will allow you to do complex things like moving, rotating and scaling some layer in the same time.
I encourage you to check the core animation programming guide

Animating the UIButton Layer?

I'm trying to bring the ripple effect seen in the dashboard application to iphone. My idea is whenever i place a button in the layout view there should be ripple effect around the button.
However, I`m able to bring the ripple effect for the whole view but I needs the effect only around the button. I don know where I went wrong. I tried the following code.
LayoutButton *tempLayoutButton=[[LayoutButton alloc] initWithObject:object];
tempLayoutButton.center=copyImage.center;
[layoutView addSubview:tempLayoutButton];
CALayer *templayer=[CALayer layer];
tempLayoutButton.layer.masksToBounds=NO;
templayer.frame=CGRectMake(0,0,50,50);
[tempLayoutButton.layer addSublayer:templayer];
CATransition *animation = [CATransition animation];
animation.delegate = self;
animation.duration = 1.0f;
animation.timingFunction = UIViewAnimationCurveEaseInOut;
animation.type = #"rippleEffect";
[templayer addAnimation:animation forKey:#"animation"];
[tempLayoutButton release];
[tempLayoutButton.layer addSublayer:templayer];
If I replace templayer with LayoutView layer I can see the riple effect from the whole view. Can anyone tell me the solution
Thanks in advance
I found the answer in one of apples mailing list. The animation is apple`s own animation and no one can use that. And there is no guarantee for the animation to appear properly in the screen. If we need the same type of animation we need to manipulate the layers and get the animation