Swift: 沿路径部分移动 UIImage

Swift: Move UIImage partly along path

我正在使用此代码沿曲线移动 UIImage:

    // paint curve for sun
    let path = UIBezierPath()

    let imageSunName = "small_sun.png"
    let imageSun = UIImage(named: imageSunName)
    let imageView = UIImageView(image: imageSun!)

    imageView.frame = CGRect(x: xStart, y: yStart, width: 24, height: 24)
    self.view.addSubview(imageView)

    path.moveToPoint(CGPoint(x: xStart,y: yStart))

    path.addQuadCurveToPoint(CGPoint(x: xEnd, y: yEnd), controlPoint: CGPoint(x: xMiddleTop, y: yMiddleTop))

    let animation = CAKeyframeAnimation(keyPath: "position")
    animation.path = path.CGPath

    animation.repeatCount = 0
    animation.duration = 5.0

    imageView.layer.addAnimation(animation, forKey: "animate position along path")

尽管如此,仍然存在两个问题:

干杯

为避免在动画结束时跳转,请在开始动画之前将图像层移动到结束位置:

imageView.layer.position = CGPoint(x: xEnd, y: yEnd)

要部分移动图像,恐怕没有简单的方法可以做到。另一种方法是根据 sunset/sunrise 计算 endPosition 和路径,这样你就不必把动画时间搞得一团糟

为了避免跳转到原来的位置添加:

animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false