8

我正在尝试为我的视图角落的圆角设置动画。cornerRadius 属性被列为动画,但我似乎无法让它工作。我实际上也无法让任何其他属性进行动画处理,但角落是我感兴趣的。这是我的代码,它非常简单:

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

self.myView.layer.cornerRadius = 50.0f;

[CATransaction commit];

我在这里想念什么?角落变得圆润,但它是瞬时的,而不是 2 秒。

4

3 回答 3

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"];
于 2011-05-04T18:00:13.313 回答
7

斯威夫特 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")

斯威夫特 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")

更新:

正如 Mark 所注意到的,使用它#keyPath来描述要设置动画的属性更简洁:

let anim1 = CABasicAnimation(keyPath: #keyPath(CALayer.cornerRadius))
于 2016-12-21T08:33:00.240 回答
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
}
于 2018-04-19T01:38:03.100 回答