将UIView的CALayer动画化为圆角

时间:2011-05-04 16:47:29

标签: ios animation core-animation rounded-corners catransition

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

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

self.myView.layer.cornerRadius = 50.0f;

[CATransaction commit];

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

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:5)

Swift 2.2 版本:

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

Swift 3.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))

答案 2 :(得分:1)

好像你正在过度思考它。我没有使用CoreAnimation就能顺利通过。这是我做的:

UIView.animate(withDuration: animationDuration) {
    self.myView.layer.cornerRadius = 10.0
}