Animating CALayer of UIView to round corners
Asked Answered
M

3

8

I'm trying to animate the rounding of the corners of my view. The cornerRadius property is listed as animatible, but I can't seem to get it to work. I actually can't get any of the other properties to animate either, but the corners are what I'm interested in. Here's my code, and it's pretty darn simple:

[CATransaction begin];
[CATransaction setValue: [NSNumber numberWithFloat: 2.0f] forKey:kCATransactionAnimationDuration];

self.myView.layer.cornerRadius = 50.0f;

[CATransaction commit];

What am I missing here guys? The corners become rounded, but it's instantaneous instead of taking 2 seconds.

Mallorie answered 4/5, 2011 at 16:47 Comment(0)
N
10
CABasicAnimation *anim1 = [CABasicAnimation animationWithKeyPath:@"cornerRadius"];
anim1.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
anim1.fromValue = [NSNumber numberWithFloat:0.0f];
anim1.toValue = [NSNumber numberWithFloat:50.0f];
anim1.duration = 2.0;
[self.myView.layer addAnimation:anim1 forKey:@"cornerRadius"];
Nucleolus answered 4/5, 2011 at 18:0 Comment(3)
where is this code located? in viewDidLoad? or viewWillAppear? or viewDidAppear?Nucleolus
It's the action of a button press.Mallorie
see above for new, improved answerNucleolus
Q
7

Swift 4.2/5:

let anim1 = CABasicAnimation(keyPath: "cornerRadius")
anim1.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
anim1.fromValue = 0
anim1.toValue = 50
anim1.duration = 2.0
layer.add(anim1, forKey: "cornerRadius")

Swift 3/4.0:

let anim1 = CABasicAnimation(keyPath: "cornerRadius")
anim1.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
anim1.fromValue = 0
anim1.toValue = 50
anim1.duration = 2.0
myView.layer.add(anim1, forKey: "cornerRadius")

Update:

As Mark noticed, it's cleaner to use #keyPath to describe the property to be animated:

let anim1 = CABasicAnimation(keyPath: #keyPath(CALayer.cornerRadius))
Quartile answered 21/12, 2016 at 8:33 Comment(1)
#keyPath(CALayer.cornerRadius) would be slightly better.Utter
S
1

Seems like you're overthinking it. I was able to get by without using CoreAnimation. Here's what I did:

UIView.animate(withDuration: animationDuration) {
    self.myView.layer.cornerRadius = 10.0
}
Simulation answered 19/4, 2018 at 1:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.