CAShapelayer 副本

CAShapelayer Duplicates

我正在尝试每 20 毫秒向给定的 x 和 y 坐标添加一次 CAShapelayer。我希望形状在一秒钟内消失(就像示踪剂一样)。我创建的功能有效,形状在正确的位置创建并消失。但是我在屏幕上留下了多余的形状。

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")

}

问题是当动画结束时,它会将 strokeColor 恢复为原始颜色。你真的应该将原始形状图层的 strokeColor 设置为 clearColor(),这样,当你完成从 whiteColor()clearColor() 的动画时,它将保持在 [=13] =].

您还可以将图层的 fillMode 设置为 kCAFillModeForwards 并将 removedOnCompletion 设置为 false,这将使图层保持其 "end of animation" 状态。但我个人只会设置 strokeColor 如上所述,因为使用 trueremovedOnCompletion 会干扰 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()
    }
}

How to remove a CALayer-object from animationDidStop?