[英]Change the frame of an UIView and update cornerRadius
在我的應用程序中,我使用UIView
子類來顯示各種信息。 我希望這些視圖顯示為圓形,因此我將視圖layer
上的cornerRadius
設置為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
動畫處理。
這是我已經嘗試過的:
UIView.animatewithDuration
運行時執行CABasicAnimation 但是所有這些都導致結果變得模糊,因為邊界尚未更新,或者在完成其他動畫之前完成添加的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()
將動畫鍵設置為“bounds”而不是“frame”。 或者您可以將這兩個動畫添加到動畫組。
您可以使用此擴展來設置角半徑變化的動畫。
extension UIView
{
func addCornerRadiusAnimation(from: CGFloat, to: CGFloat, duration: CFTimeInterval)
{
let animation = CABasicAnimation(keyPath:"cornerRadius")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.fromValue = from
animation.toValue = to
animation.duration = duration
self.layer.addAnimation(animation, forKey: "cornerRadius")
self.layer.cornerRadius = to
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.