2016-05-31 102 views

回答

2

嘗試動畫您層的邊界:

let a = CALayer() 
a.bounds = CGRect(x: 0, y: 0, width: 100, height: 40) 
a.position = CGPoint(x: 20, y: 20) 
a.anchorPoint = CGPoint(x: 0, y: 0) 
view.layer.addSublayer(a) 

let anim = CABasicAnimation(keyPath: "bounds") 
anim.duration = 2 
anim.fromValue = NSValue(CGRect: CGRect(x: 0, y: 0, width: 0, height: 30)) 
anim.toValue = NSValue(CGRect: CGRect(x: 0, y: 0, width: 100, height: 30)) 
a.addAnimation(anim, forKey: "anim") 

它爲我工作。只是不要忘記設置achor點。

+0

我應用此代碼,但它的寬度不隨動畫增加。當我運行該應用程序時,它向我顯示具有fillcolor的圖層。而且它從視圖的中間開始。 –

+1

Stefos的一個小小的修改answer.Just用「bounds.size.width」代替keypath,只是給你的寬度,如fromValue和100,toValue.Hope它有幫助。 –

+0

選擇寬度動畫(增長還是縮小)完全在一個方向還是兩個方向的魔力在於您正在動畫的圖層的anchorPoint。 (0.5,0.5)的默認定位點意味着寬度的增長或收縮在兩側均勻發生。 (0,0)的定位點意味着圖層本質上固定在左上角,所以無論新寬度如何,改變都發生在右側。也就是說,重要的不是您的動畫關鍵路徑是「bounds」還是「bounds.size.width」。定位點決定了變化發生的位置。 –

0

回答斯威夫特3. 爲使該層從左邊(而不是從中心!)向右我用下面的方法改變其寬度:

我有一個名爲「圖層」圖層,我想改變它寬度從0到myWidth

layer.position = CGPoint(x: 0, y: 0) 
layer.anchorPoint = CGPoint(x: 0, y: 0.5) 
let layerAnimation = CABasicAnimation(keyPath: "bounds.size.width") 
layerAnimation.duration = 2 
layerAnimation.fromValue = 0 
layerAnimation.toValue = myWidth 
layer.add(layerAnimation, forKey: "anim")