[swift]CAShapelayer 重复项

标签: Swift
发布时间: 2017/3/6 22:57:16
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我试图将 CAShapelayer 一次每 20ms年添加到给定 x 和 y 坐标。我会喜欢它的形状会逐渐消失,超过一秒钟 (就像一种示踪剂)。我已经创建了作品的功能,该形状在正确的位置中创建,消失了。但我得到额外留下打乱屏幕的形状。

func shadowBall (x: CGFloat, y: CGFloat){

    let xpos : CGFloat = ((self.frame.width/2) + x)
    let ypos : CGFloat = ((self.frame.height/2) + y)

    let shadowBall = CAShapeLayer()
    let shadowBalllRadius :CGFloat = 4
    let shadowBallPath : UIBezierPath = UIBezierPath(ovalInRect: CGRect(x: xpos, y: ypos, width: CGFloat(shadowBalllRadius*2), height: CGFloat(shadowBalllRadius*2)))

    shadowBall.path = shadowBallPath.CGPath
    shadowBall.fillColor = UIColor.clearColor().CGColor
    shadowBall.strokeColor = UIColor.whiteColor().CGColor
    shadowBall.lineWidth = 0.5

    let animation: CABasicAnimation = CABasicAnimation(keyPath: "strokeColor")
    animation.fromValue = UIColor.whiteColor().CGColor
    animation.toValue = UIColor.clearColor().CGColor
    animation.duration = 1.0;
    animation.repeatCount = 0;
    animation.removedOnCompletion = true
    animation.additive = false

    self.layer.addSublayer(shadowBall)
    shadowBall.addAnimation(animation, forKey: "strokeColor")

}

解决方法 1:

问题是当动画完成后,它将恢复 strokeColor 为原始颜色。你真的应该设置 strokeColor 的原始形状图层是 clearColor() ,这样一来,当你完成动画从 whiteColor()clearColor() ,它将保持在 clearColor()

您还可以设置图层的 fillModekCAFillModeForwards 和设置 removedOnCompletionfalse ,会保留其"动画结束"状态的图层。但我个人只是设置 strokeColor 如上所述,使用 removedOnCompletiontrue 干扰 animationDidStop (见下文)。


此外,我可能会建议你也删除图层,一旦它完成与动画,所以它不会继续消耗内存,虽然它不再是可见。

func shadowBall (x: CGFloat, y: CGFloat) {
    let xpos: CGFloat = ((self.frame.width/2) + x)
    let ypos: CGFloat = ((self.frame.height/2) + y)

    let shadowBall = CAShapeLayer()
    let shadowBalllRadius: CGFloat = 4
    let shadowBallPath = UIBezierPath(ovalInRect: CGRect(x: xpos, y: ypos, width: CGFloat(shadowBalllRadius*2), height: CGFloat(shadowBalllRadius*2)))

    shadowBall.path = shadowBallPath.CGPath
    shadowBall.fillColor = UIColor.clearColor().CGColor
    shadowBall.strokeColor = UIColor.clearColor().CGColor
    shadowBall.lineWidth = 0.1

    let animation = CABasicAnimation(keyPath: "strokeColor")
    animation.fromValue = UIColor.whiteColor().CGColor
    animation.toValue = UIColor.clearColor().CGColor
    animation.duration = 1.0
    animation.repeatCount = 0
    animation.removedOnCompletion = true
    animation.additive = false

    animation.delegate = self
    animation.setValue(shadowBall, forKey: "animationLayer")

    self.layer.addSublayer(shadowBall)
    shadowBall.addAnimation(animation, forKey: "strokeColor")
}

override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
    if let layer = anim.valueForKey("animationLayer") as? CALayer {
        layer.removeFromSuperlayer()
    }
}

请参阅如何删除一个 CALayer 对象从 animationDidStop?

官方微信
官方QQ群
31647020