简体   繁体   中英

Animating CALayer of UIView to round corners

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.

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"];

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))

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM