在我的应用程序中,我正在使用UIView
子类来显示各种信息。我希望此视图显示为圆形,因此将视图cornerRadius
上的layer
设置为self.bounds.size.width / 2
。
这可以按预期工作,直到我尝试为其设置动画。我使用UIView.animateWithDuration
为我的视图设置动画,例如:
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.myView.frame = CGRectInset(self.myView.frame, -20, -20);
}) { (done) -> Void in
}
我希望我的视图还可以在同一动画(或单独的动画)中更新图层的cornerRadius,因为cornerRadius的更改未使用
animateWithDuration
进行动画处理。这是我已经尝试过的:
但是所有这些都会导致错误的结果,因为要么尚未更新边界,要么在其他动画完成之前完成了所添加CALayer的调整大小。我希望它是一个平稳的过渡。
最佳答案
func changeBounds()
{
let animation = CABasicAnimation()
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.fromValue = NSValue(CGRect: self.theView.frame)
animation.toValue = NSValue(CGRect: CGRectInset(self.theView.frame, 40, 40))
animation.duration = 1.0
self.theView.layer.addAnimation(animation, forKey: "bounds")
CATransaction.begin()
CATransaction.setDisableActions(true)
self.theView.layer.frame = CGRectInset(self.theView.frame, 40, 40)
CATransaction.commit()
}
func changeCornerRadius()
{
let animation = CABasicAnimation(keyPath:"cornerRadius")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.fromValue = 0
animation.toValue = self.theView.frame.size.width/2
animation.duration = 1.0
self.theView.layer.addAnimation(animation, forKey: "cornerRadius")
self.theView.layer.cornerRadius = self.theView.frame.size.width/2
}
像这样打电话给我,这似乎对我有用。
self.changeBounds()
self.changeCornerRadius()
将动画关键点设置为“边界”,而不是“帧”。或者,您可以将这两个动画添加到动画组中。