动画CALayer的shadowPath属性
我知道CALayer的shadowPath只能使用显式动画制作动画,但是我仍然无法使其工作。 我怀疑我没有正确传递toValue
– 据我所知这必须是一个id
,但该属性需要一个CGPathRef。 将其存储在UIBezierPath
中似乎不起作用。 我使用以下代码进行测试:
CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"shadowPath"]; theAnimation.duration = 3.0; theAnimation.toValue = [UIBezierPath bezierPathWithRect:CGRectMake(-10.0, -10.0, 50.0, 50.0)]; [self.view.layer addAnimation:theAnimation forKey:@"animateShadowPath"];
(我使用负值,以确保阴影延伸masksToBounds
顶部的视图之外…图层的masksToBounds
属性设置为NO
)。
shadowPath的动画是如何实现的?
UPDATE
问题差点解决了。 不幸的是,主要问题是有点粗心的错误……
我犯的错误是将动画添加到视图控制器的根层,而不是我专用于阴影的图层。 另外,@ pe8ter是正确的,因为toValue需要是一个CGPathRef
为id
(显然当我尝试这个之前,由于错误的图层错误,我仍然没有动画)。 动画使用以下代码:
CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"shadowPath"]; theAnimation.duration = 3.0; theAnimation.toValue = (id)[UIBezierPath bezierPathWithRect:myRect].CGPath; [controller.shadowLayer addAnimation:theAnimation forKey:@"shadowPath"];
我很感激这很难从我提供的示例代码中找到。 希望它仍然可以用于处于类似情况的人。
但是,当我尝试添加该行时
controller.shadowLayer.shadowPath = [UIBezierPath bezierPathWithRect:myRect].CGPath;
动画停止工作,阴影立即跳到最终位置。 文档说添加动画时使用与要更改的属性相同的键,以覆盖设置属性值时创建的隐式动画,但是shadowPath无法生成隐式动画…所以如何获取新属性留在动画后?
首先,您没有设置动画的fromValue
。
其次,你是对的: CGPathRef
接受一个CGPathRef
,除了需要转换为id
。 做这样的事情:
theAnimation.toValue = (id)[UIBezierPath bezierPathWithRect:newRect].CGPath;
如果希望在动画之后保留更改,则还需要显式设置图层的shadowPath
属性。
let cornerRadious = 10.0 // let shadowPathFrom = UIBezierPath(roundedRect: rect1, cornerRadius: cornerRadious) let shadowPathTo = UIBezierPath(roundedRect: rect2, cornerRadius: cornerRadious) // layer.masksToBounds = false layer.shadowColor = UIColor.yellowColor().CGColor layer.shadowOpacity = 0.6 // let shadowAnimation = CABasicAnimation(keyPath: "shadowPath") shadowAnimation.fromValue = shadowPathFrom.CGPath shadowAnimation.toValue = shadowPathTo.CGPath shadowAnimation.duration = 0.4 shadowAnimation.autoreverses = true shadowAnimation.removedOnCompletion = true shadowAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) layer.addAnimation(shadowAnimation, forKey: "shadowAnimation")