I'm trying to animate the change of the cornerRadius
of a UIView
instance layer
, but the variation of the cornerRadius
takes place immediately.
Here's the code:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
view.layer.masksToBounds = YES;
view.layer.cornerRadius = 10.0;
[UIView animateWithDuration:1.0 animations:^{
[view.layer.cornerRadius = 0.0;
}];
Thanks everybody who is going to give me any tips.
EDIT:I managed to animate this property using Core Animation
, using a CABasicAnimation
.
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"cornerRadius"];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.fromValue = [NSNumber numberWithFloat:10.0f];
animation.toValue = [NSNumber numberWithFloat:0.0f];
animation.duration = 1.0;
[viewToAnimate.layer addAnimation:animation forKey:@"cornerRadius"];
[animation.layer setCornerRadius:0.0];
tl;dr: Corner radius is not animatable in
animateWithDuration:animations:
.What the documentation says about view animations.
As the section on Animations in the "View Programming Guide for iOS" says
The full list of properties that you can animate using either the older
or the newer
(that you are using) are:
As you can see,
cornerRadius
is not in the list.Some confusion
UIView animations is really only meant for animating view properties. What confuses people is that you can also animate the same properties on the layer inside the UIView animation block, i.e. the frame, bounds, position, opacity, backgroundColor. So people see layer animations inside
animateWithDuration
and believe that they can animate any view property in there.The same section goes on to say:
A few lines down you can read the list of Core Animation animatable properties where you see this one:
So to animate the
cornerRadius
you need to use Core Animation as you've already said in your updated question (and answer). I just added tried to explain why its so.Some extra clarification
When people read the documentations that says that
animateWithDuration
is the recommended way of animating it is easy to believe that it is trying to replace CABasicAnimation, CAAnimationGroup, CAKeyframeAnimation, etc. but its really not. Its replacing thebeginAnimations:context:
andcommitAnimations
that you seen above.CornerRadius property is animatable
working code is below
//layer init
// animation init
You can make this property animatable in
+[UIView animateWithDuration:]
by implementing-[actionForLayer:forKey]
in your view class. See this question for an example of how.Doesn't look like that's one of the animatable properties.
See here for the full list:
http://developer.apple.com/library/ios/#documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/AnimatingViews/AnimatingViews.html
I use this extension to animate change of corner radius:
Starting in iOS 10 you can actually animate cornerRadius: