2016-05-31 107 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")