我正在创建一个随机UIBezierPath
,设置CAShapeLayer
.path
属性的路径,然后设置CAShapeLayer
&#的动画中风如此:
// Get a path
let path = createBezierPath()
// Shape layer properties
let color = randomCGColor() // Color of path and shadow
let lineWidth = CGFloat(arc4random_uniform(50) + 11) // Width of line and shadow radius
shapeLayer.path = path.CGPath
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineCap = kCALineCapRound
shapeLayer.strokeColor = color
shapeLayer.lineWidth = lineWidth
shapeLayer.fillColor = UIColor.clearColor().CGColor
// Shape layer shadow properties
shapeLayer.shadowPath = path.CGPath
shapeLayer.shadowColor = color
shapeLayer.shadowOffset = CGSizeZero
shapeLayer.shadowRadius = lineWidth
shapeLayer.shadowOpacity = 1.0
// Add shape layer
self.layer.addSublayer(shapeLayer)
// Stroke path animation
let pathAnimation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.fromValue = 0.0
pathAnimation.toValue = 1.0
// Shadow path animation
let shadowPathAnimation: CABasicAnimation = CABasicAnimation(keyPath: "shadowPath")
shadowPathAnimation.fromValue = 0.0
shadowPathAnimation.toValue = path.CGPath
// Animation group
let animationGroup = CAAnimationGroup()
animationGroup.duration = 5.0
animationGroup.animations = [pathAnimation, shadowPathAnimation]
shapeLayer.addAnimation(animationGroup, forKey: "allMyAnimations")
问题是,一旦动画完成,阴影就会应用到整个形状。我喜欢将阴影应用于CAShapeLayer
的中风。 如何在动画完成后阻止阴影应用于整个形状?
以下是我所指的问题的一个例子:
答案 0 :(得分:7)
我能够在this answer的帮助下,通过为阴影创建CALayer
并将CAShapeLayer
添加为子图层来解决问题:
let path = createBezierPath() // Get a path
let color = randomCGColor() // Color of path and shadow
let lineWidth = CGFloat(arc4random_uniform(50) + 11) // Width of line and shadow radius
// Shape layer properties
shapeLayer.path = path.CGPath
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineCap = kCALineCapRound
shapeLayer.strokeColor = color
shapeLayer.lineWidth = lineWidth
shapeLayer.fillColor = UIColor.clearColor().CGColor
// Create shadow layer
let shadowLayer = CALayer()
shadowLayer.frame = self.bounds
shadowLayer.shadowColor = color
shadowLayer.shadowOffset = CGSizeZero
shadowLayer.shadowRadius = lineWidth
shadowLayer.shadowOpacity = 1.0
shadowLayer.backgroundColor = UIColor.clearColor().CGColor
shadowLayer.insertSublayer(shapeLayer, atIndex: 0)
// Add shadow layer
self.layer.addSublayer(shadowLayer)
// Stroke path animation
let pathAnimation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.fromValue = 0.0
pathAnimation.toValue = 1.0
pathAnimation.duration = 5.0
shapeLayer.addAnimation(pathAnimation, forKey: "strokeAnimation")
// Shadow path animation
let shadowPathAnimation: CABasicAnimation = CABasicAnimation(keyPath: "shadowPath")
shadowPathAnimation.fromValue = 0.0
shadowPathAnimation.toValue = path.CGPath
shadowLayer.addAnimation(shadowPathAnimation, forKey: "shadowAnimation")
结果示例: