0

我已将此动画写入 CAShapeLayer (pulseLayer) 并在viewDidLoad()

let pulseLayer = CAShapeLayer()
@IBOutlet weak var btnCart: UIButton!

override func viewDidLoad() {
    let longpress = UILongPressGestureRecognizer(target: self, action: #selector(CategoryViewController.longPressGestureRecognized(_:)))
    tableView.addGestureRecognizer(longpress)

    heartBeatAnimation.duration       = 0.75
    heartBeatAnimation.repeatCount    = Float.infinity
    heartBeatAnimation.autoreverses   = true
    heartBeatAnimation.fromValue      = 1.0
    heartBeatAnimation.toValue        = 1.2
    heartBeatAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)

    btnCart.layer.addSublayer(pulseLayer)
}

func addBtnCartLayerWithAnimation() {
    let ovalPath = UIBezierPath(arcCenter: CGPoint(x: btnCart.frame.midX, y: btnCart.frame.midY), radius: btnCart.frame.width * 1.5, startAngle: 0*(CGFloat.pi / 180), endAngle: 360*(CGFloat.pi / 180), clockwise: true)

    pulseLayer.path = ovalPath.cgPath
    pulseLayer.opacity = 0.15
    pulseLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    pulseLayer.bounds = ovalPath.cgPath.boundingBox
    pulseLayer.add(heartBeatAnimation, forKey: "heartBeatAnimation")
    pulseLayer.transform = CATransform3DScale(CATransform3DIdentity, 1.0, 1.0, 1.0)
}

removeLayer 函数是:

func removeLayer() {
    pulseLayer.transform = CATransform3DScale(CATransform3DIdentity, 0.1, 0.1, 0.1)
    pulseLayer.removeAllAnimations()
}

问题是当图层的第一个动画来自视图的底部时!

viewDidLoad 之后的第一个动画

然后从中心(定义的锚点)开始对此动画的任何调用

第一个之后的任何动画

谁能告诉我为什么会这样?

我在 tableView 上定义和使用的整个类UILongGestureRecognizer来启动/停止动画:

func longPressGestureRecognized(_ gestureRecognizer: UIGestureRecognizer) {
    let longPress = gestureRecognizer as! UILongPressGestureRecognizer
    let state = longPress.state
    let locationInView = longPress.location(in: tableView)
    let indexPath = tableView.indexPathForRow(at: locationInView)

    switch state {
    case UIGestureRecognizerState.began:
        if indexPath != nil {
            addBtnCartLayerWithAnimation()
        }

    case UIGestureRecognizerState.changed:
        // some code here not related to the animation 
    default:
        removeLayer()
    }
}
4

1 回答 1

1

使用独立层(不是 a 的后备存储的层UIView)时,会为每个可动画属性更改添加隐式动画。

您会看到这种效果,因为该图层正在将其属性从零设置为您在 中设置的初始值addBtnCartLayerWithAnimation()

您要做的是在没有动画的情况下设置这些初始值(这需要明确地完成)。您可以将更改包装在禁用动画的事务中,如下所示:

CATransaction.begin()
CATransaction.setDisableActions(true)

pulseLayer.path = ovalPath.cgPath
pulseLayer.opacity = 0.15
pulseLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
pulseLayer.bounds = ovalPath.cgPath.boundingBox
pulseLayer.transform = CATransform3DScale(CATransform3DIdentity, 1.0, 1.0, 1.0)

CATransaction.commit()

pulseLayer.add(heartBeatAnimation, forKey: "heartBeatAnimation")
于 2017-08-01T10:53:04.953 回答