Mimic UIAlertView Bounce? - ios

Whats the best way to mimic the bouncing animation from the UIAlertView on the iPhone? Is there some built-in mechanism for this? The UIAlertView itself won't work for my needs.
I looked into animation curves but from what I can tell the only ones they provide are easeIn, easeOut, and linear.

UIAlertView uses a more sophisticated animation:
scale to larger than 100%
scale to smaller than 100%
scale to 100%
Here's an implementation using a CAKeyFrameAnimation:
view.alpha = 0;
[UIView animateWithDuration:0.1 animations:^{view.alpha = 1.0;}];
CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:#"transform.scale"];
bounceAnimation.values = #[#0.01f, #1.1f, #0.8f, #1.0f];
bounceAnimation.keyTimes = #[#0.0f, #0.5f, #0.75f, #1.0f];
bounceAnimation.duration = 0.4;
[view.layer addAnimation:bounceAnimation forKey:#"bounce"];

I investigated how animations are added to UIAlertView's layer by swizzling -[CALayer addAnimation:forKey:]. Here are the values I got for the scale transform animations it performs:
0.01f -> 1.10f -> 0.90f -> 1.00f
with durations
0.2s, 0.1s, 0.1s.
All the animations use an ease in/ease out timing function. Here is a CAKeyframeAnimation that encapsulates this logic:
CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:#"transform"];
bounceAnimation.fillMode = kCAFillModeBoth;
bounceAnimation.removedOnCompletion = YES;
bounceAnimation.duration = 0.4;
bounceAnimation.values = #[
[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 0.01f)],
[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.1f)],
[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 0.9f)],
[NSValue valueWithCATransform3D:CATransform3DIdentity]];
bounceAnimation.keyTimes = #[#0.0f, #0.5f, #0.75f, #1.0f];
bounceAnimation.timingFunctions = #[
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
I believe UIAlertView also performs a simple opacity animation from 0.0f to 1.0f over the total duration of the transform animation (0.4).

You can use 2 animations, one to pop up to very large, and the other one to rescale back to normal size.
(This is the approach use by UIAlertView internally.)
Alternatively, you can use the lower-level CAAnimation and use +[CAMediaTimingFunction functionWithControlPoints::::] to make your own curve.

Here's how I did it for an app I'm working on. The effect I was going for was bouncing when you pressed the view. Experiment with the values to suit your taste and the desired speed of the effect.
- (void) bounceView:(UIView*)bouncer
{
// set duration to whatever you want
float duration = 1.25;
// use a consistent frame rate for smooth animation.
// experiment to your taste
float numSteps = 15 * duration;
// scale the image up and down, halving the distance each time
[UIView animateKeyframesWithDuration:duration
delay:0
options:UIViewKeyframeAnimationOptionCalculationModeCubic
animations:^{
float minScale = 0.50f; // minimum amount of shrink
float maxScale = 1.75f; // maximum amount of grow
for(int i = 0; i< numSteps*2; i+=2)
{
// bounce down
[UIView addKeyframeWithRelativeStartTime:duration/numSteps * i
relativeDuration:duration/numSteps
animations:^{
bouncer.layer.transform = CATransform3DMakeScale(minScale, minScale, 1);
}];
// bounce up
[UIView addKeyframeWithRelativeStartTime:duration/numSteps * (i+1)
relativeDuration:duration/numSteps
animations:^{
bouncer.layer.transform = CATransform3DMakeScale(maxScale, maxScale, 1);
}];
// cut min scale halfway to identity
minScale = minScale + (1.0f - minScale) / 2.0f;
// cut max scale halfway to identity
maxScale = 1.0f + (maxScale - 1.0f) / 2.0f;
}
} completion:^(BOOL finished) {
// quickly smooth out any rounding errors
[UIView animateWithDuration:0.5*duration/numSteps animations:^{
bouncer.layer.transform = CATransform3DIdentity;
}];
}];
}

Related

CABasicAnimation flicker when applying the completion

I am trying to apply a rotation animation by number of degrees to a UIImageView and persist the rotation transformation in the completion block.
The problem that I am facing is that when the completion block is executed there is a visible flicker generated by passing from the end state of the animation to the completion block.
Here is the code that I am currently using:
if (futureAngle == currentAngle) {
return;
}
float rotationAngle;
if (futureAngle < currentAngle) {
rotationAngle = futureAngle - currentAngle;
}else{
rotationAngle = futureAngle - currentAngle;
}
float animationDuration = fabs(rotationAngle) / 100;
rotationAngle = GLKMathDegreesToRadians(rotationAngle);
[CATransaction begin];
CABasicAnimation *rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
rotationAnimation.byValue = [NSNumber numberWithFloat:rotationAngle];
rotationAnimation.duration = animationDuration;
rotationAnimation.removedOnCompletion = YES;
[CATransaction setCompletionBlock:^{
view.transform = CGAffineTransformRotate(view.transform, rotationAngle);
}];
[view.layer addAnimation:rotationAnimation forKey:#"rotationAnimation"];
[CATransaction commit];
When you say flicker, I assume you mean that at the end of the animation, that it momentarily returns to the initial state before returning back to the final state? This can be solved either by
setting the final view.transform before you start the animation (and you no longer need the completionBlock);
by setting the animation's fillMode to kCAFillModeForwards and set removedOnCompletion to false.
Personally, I think setting the animated property to its destination value before you start the animation is the easiest way to do this.
Thus:
- (void)rotate:(UIView *)view by:(CGFloat)delta {
float animationDuration = 2.0;
CGFloat currentAngle = self.angle; // retrieve saved angle
CGFloat nextAngle = self.angle + delta; // increment it
self.angle = nextAngle; // save new value
view.transform = CGAffineTransformMakeRotation(nextAngle); // set property to destination rotation
CABasicAnimation *rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"]; // now rotate
rotationAnimation.fromValue = #(currentAngle);
rotationAnimation.toValue = #(nextAngle);
rotationAnimation.duration = animationDuration;
rotationAnimation.removedOnCompletion = YES;
[view.layer addAnimation:rotationAnimation forKey:#"rotationAnimation"];
}
Or, I think even easier, just adjust the transform:
- (void)rotate:(UIView *)view by:(CGFloat)delta {
float animationDuration = 2.0;
CGAffineTransform transform = view.transform; // retrieve current transform
CGAffineTransform nextTransform = CGAffineTransformRotate(transform, delta); // increment it
view.transform = nextTransform; // set property to destination rotation
CABasicAnimation *rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform"]; // now rotate
rotationAnimation.fromValue = [NSValue valueWithCGAffineTransform:transform];
rotationAnimation.toValue = [NSValue valueWithCGAffineTransform:nextTransform];
rotationAnimation.duration = animationDuration;
rotationAnimation.removedOnCompletion = YES;
[view.layer addAnimation:rotationAnimation forKey:#"rotationAnimation"];
}
I was seeing flickering even when using the suggested answer from Rob, but turns out it seems to just be a simulator bug. On real devices I dont see the flicker, if you have only been testing on simulator, try on a real device unless you want to waste hours of your life potentially like myself.

Rotating iOS UILayer like a ticking clock, not smoothly in a circle

I am able to rotate an image a certain number of degrees continuously, but I want to rotate the image a tiny amount, pause, a little more, pause, etc.
The follow code does this continuously:
// rotate
CGFloat finalValue = 360 / 14.f;
CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
[rotationAnimation setFromValue:[self degreesToNumber:0]];
[rotationAnimation setToValue:[self degreesToNumber:finalValue]];
[rotationAnimation setDuration:5.0];
[rotationAnimation setRemovedOnCompletion:NO];
[rotationAnimation setFillMode:kCAFillModeForwards];
[self.secondHandImageView.layer addAnimation:rotationAnimation forKey:#"rotate"];
Is there a way to wrap this in a for-loop with the number of angle changes I need and set the duration and delay of the specific animations? Nothing I have tried works. Below is what I am currently trying:
// rotate in ticks, so
NSTimeInterval delay = 0;
CGFloat currentAngle = 0;
CGFloat finalAngle = 360 / 14.f;
// angle difference
CGFloat numberOfTicks = 25.f;
CGFloat angleDelta = finalAngle / numberOfTicks;
for (NSUInteger tick = 0; tick < numberOfTicks; tick++) {
[UIView animateWithDuration:0.1 delay:delay options:UIViewAnimationOptionCurveLinear animations:^{
self.secondHandImageView.layer.transform = CATransform3DMakeRotation(0, 0, angleDelta, 1.0);
} completion:nil];
// update delay
delay += .2; // 200 milliseconds, 5 tickets every second
currentAngle += angleDelta;
}
You code is OK - except that you can't animate layers inside UIView animation blocks. Instead you can animate the view. Replace the (3D)layer transform with a (2D)view transform:
self.secondHandImageView.transform =
CGAffineTransformRotate(self.tickView.transform,angleDelta);

How can I replace CGAffineTransform scale and alpha animations using CABasicAnimations and Auto Layout?

As far as I can see, Apple wants us to move away from CGAffineTransform animations and into animations using:
myView.layoutConstraint.constant = someNewValue;
[myView layoutIfNeeded];
for animations that involve a translation of a view.
It also seems we should be now using CABasicAnimation animations for scale and rotation (and sometimes opacity) because it animates the view's layer and not the view and in doing so, plays nicely with auto layout.
I used the following code to apply an opacity and scale animation that worked beautifully:
[UIView animateWithDuration:0.1f animations:^{
// first animation
self.myMeButton.alpha = 1;
self.myMeButton.transform = CGAffineTransformMakeScale(1.1, 1.1);
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.2f animations:^{
// second animation
self.myButton.transform = CGAffineTransformMakeScale(1, 1);
}];
}];
Of course auto layout plays havoc with the scale animation and so I am trying to find an alternative way to do it. So far, I have come up with this:
[CATransaction begin]; {
[CATransaction setCompletionBlock:^{
// code for when animation completes
self.pickMeButton.alpha = 1;
CABasicAnimation *scaleDown = [CABasicAnimation animationWithKeyPath:#"scale"];
scaleDown.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1)];
scaleDown.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)];
scaleDown.duration = 0.1;
[self.myButton.layer addAnimation:scaleDown forKey:nil];
}];
// describe animations:
CABasicAnimation* scaleUp = [CABasicAnimation animationWithKeyPath:#"scale"];
scaleUp.autoreverses = NO;
scaleUp.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)];
scaleUp.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1)];
CABasicAnimation *fadeAnim = [CABasicAnimation animationWithKeyPath:#"opacity"];
fadeAnim.fromValue=[NSNumber numberWithDouble:0.0];
fadeAnim.toValue=[NSNumber numberWithDouble:1.0];
// Customization for all animations:
CAAnimationGroup *group = [CAAnimationGroup animation];
group.duration = 0.2f;
group.repeatCount = 1;
group.autoreverses = NO;
group.animations = #[scaleUp, fadeAnim];
// add animations to the view's layer:
[self.myButton.layer addAnimation:group forKey:#"allMyAnimations"];
} [CATransaction commit];
As you can see the code almost 3 times as long as before and the animation on the device is noticeably less 'smooth' than it was previously.
Is there any way to do this better?
Thanks in advance for your response.
EDIT: This seems to have done the trick in that the animations are smooth, but I still feel like the code for this could be a lot more succinct.
[UIView animateWithDuration:0.2f animations:^{
self.pickMeButton.alpha = 1;
CABasicAnimation* scaleUp = [CABasicAnimation animationWithKeyPath:#"transform"];
scaleUp.duration = 0.2;
scaleUp.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1)];
scaleUp.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1)];
[self.pickMeButton.layer addAnimation:scaleUp forKey:nil];
}completion:^(BOOL finished) {
CABasicAnimation* scaleDown = [CABasicAnimation animationWithKeyPath:#"transform"];
scaleDown.duration = 0.1;
scaleDown.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1)];
scaleDown.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)];
[self.pickMeButton.layer addAnimation:scaleDown forKey:nil];
}];
I don't know why you want to do it with CABasicAnimation for scale. You can do it like you mention at the top of your question. Set a new value for the view's width and height constraint constant values and then use [myView layoutIfNeeded] inside animateWithDuration. If the view doesn't have height and width constraints, but has constants to the top and bottom and/or left and right edges of the superview, change those values instead.

IOS Need to rotate a Image and keep it there, with animation

im looking to Rotate a UIImageView, and i found some helpfull code
- (void) runSpinAnimationOnView:(UIView*)view duration:(CGFloat)duration rotations: (CGFloat)rotations repeat:(float)repeat;
{
CABasicAnimation* rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 /* full rotation*/ * rotations * duration ];
rotationAnimation.duration = duration;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = repeat;
[view.layer addAnimation:rotationAnimation forKey:#"rotationAnimation"];
}
The issue is that the image flips back when the animation finishes, im looking to rotate it and keep it there. Would i need to flip the actual image or can i flip the ImageView. And how would i do that`?
Why not use a standard UIView animation?
If you really need the repeatCount, then I suggest you use the old style:
[UIView beginAnimations]
[UIView setAnimationRepeatCount:repeatCount];
[UIView setAnimationDuration:duration];
yourView.transform = CGAffineTransformMakeRotation(degrees * M_PI);
[UIView commitAnimations];
Otherwise, you can use the much preferred new style:
[UIView animateWithDuration:duration animations:^{
yourView.transform = CGAffineTransformMakeRotation(angle);
} completion:^(BOOL finished) {
// your completion code here
}]
If you need other options like autoreverse, allow user interaction or repeating use [UIView animateWithDuration:delay:options:animations:completion:];
I prefer to cover all my bases with CoreAnimation. Set the final value before the animation, set the fill mode, and set do not remove.
- (void) runSpinAnimationOnView:(UIView*)view duration:(CGFloat)duration rotations: (CGFloat)rotations repeat:(float)repeat;
{
NSString * animationKeyPath = #"transform.rotation.z";
CGFloat finalRotation = M_PI * 2.0f * rotations;
[view.layer setValue:#(finalRotation) forKey:animationKeyPath];
CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:animationKeyPath];
rotationAnimation.fromValue = #0.0f;
rotationAnimation.toValue = #(finalRotation);
rotationAnimation.fillMode = kCAFillModeBoth;
rotationAnimation.removedOnCompletion = NO;
rotationAnimation.duration = duration;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = repeat;
[view.layer addAnimation:rotationAnimation forKey:#"rotationAnimation"];
}

Multiple CALayer animations Executed at the Same time

I am trying to make an animation where two layers move to the side, scale down, and rotate a little bit in 3D, all at the same time (then move back with the layer previously at the bottom not on top). I tried several methods, but none seem to work.
I have the 3d transform animation like so:
perspectiveTransformLeft = CATransform3DIdentity;
perspectiveTransformLeft.m34 = 1.0 / 500;
perspectiveTransformLeft = CATransform3DRotate(perspectiveTransformLeft, 35.0f * M_PI / 360.0f, 0.0f, 1.0f, 0.0f);
I've tried adding a scale transform that didn't work:
perspectiveTransformLeft = CATransform3DMakeScale(0.75, 0.75, 1);
I've tried to scale the layer in an animation block, but that didn't work either:
[UIView animateWithDuration:1.0f
delay:0.0f
options: UIViewAnimationOptionCurveEaseInOut
animations:^{
endingLayer.frame = CGRectMake(20.0f, 0.0f, 724.0f, 538.0f);
switchViewBottom.layer.transform = perspectiveTransformRight;
}
completion:^(BOOL finished){
[delegate switchAnimationFinished];
}
];
I am at a loss. Can someone help me?
Do some reading on CAAnimationGroup and use CABasicAnimations instead.
That should held you achieve what you're after. I'll search for an example in my code (I previously used it) if you'll have issues implementing it.
Edit: Here's some code
typedef void (^animationCompletionBlock)(void);
typedef void (^animationStartedBlock)(void);
- (void)addAnimations:(NSArray *)animations withDuration:(CGFloat)animationDuration onView:(UIView *)aView {
animationStartedBlock startBlock = ^void(void) {
// Additional Animation start code here
};
animationCompletionBlock endBlock = ^void(void) {
// Additional animation completed code here
};
CAAnimationGroup *group = [CAAnimationGroup animation];
group.fillMode = kCAFillModeForwards;
group.removedOnCompletion = NO;
group.duration = animationDuration;
[group setAnimations:animations];
group.delegate = self;
[group setValue:startBlock forKey:#"animationStartedBlock"];
[group setValue:endBlock forKey:#"animationCompletionBlock"];
[aView.layer addAnimation:group forKey:#"yourAnimationName"];
}
This will have your completion blocks called in your delegate
// Animation Delegate
- (void)animationDidStart:(CAAnimation *)anim {
animationStartedBlock animationStartedBlock = [anim valueForKey:#"animationStartedBlock"];
if (animationStartedBlock) {
animationStartedBlock();
}
}
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
animationCompletionBlock animationCompleteBlock = [theAnimation valueForKey:#"animationCompletionBlock"];
if (animationCompleteBlock) {
animationCompleteBlock();
}
}
How you create the animations and add them to an array to pass to this method is up to you, depending on what animations you want.
This is an example for two scale / fade animations:
// Scale
- (CABasicAnimation *)scaleAnimationForImageView:(UIImageView *)imageView withDuration:(CGFloat)duration {
CGRect imageFrame = imageView.frame;
CABasicAnimation *resizeAnimation = [CABasicAnimation animationWithKeyPath:#"bounds.size"];
[resizeAnimation setToValue:[NSValue valueWithCGSize:CGSizeMake(40.0f, imageFrame.size.height * (40.0f / imageFrame.size.width))]];
resizeAnimation.fillMode = kCAFillModeForwards;
resizeAnimation.duration = duration;
resizeAnimation.removedOnCompletion = NO;
return resizeAnimation;
}
// Fade
- (CABasicAnimation *)fadeAnimationWithFinalOpacity:(CGFloat)opacity withDuration:(CGFloat)duration {
CABasicAnimation *fadeOutAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
[fadeOutAnimation setToValue:[NSNumber numberWithFloat:opacity]];
fadeOutAnimation.fillMode = kCAFillModeForwards;
fadeOutAnimation.removedOnCompletion = NO;
fadeOutAnimation.duration = duration;
return fadeOutAnimation;
}

Resources