Swift: Move UIImage partly along path

2019-04-07 19:11发布

I am using this code to move a UIImage along a curve:

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

Nevertheless, two issues remain:

  • I would like to move the image only partly along the path (according to the current time vs sunrise/sunset) - how can this be done?
  • The image jumps to its origin position after the animation stopped - how can I avoid this?

Cheers

2条回答
Luminary・发光体
2楼-- · 2019-04-07 19:51

To avoid jump to its original position add:

animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
查看更多
欢心
3楼-- · 2019-04-07 19:54

To avoid jumping on animation end, just before starting animation move your image layer to the end position:

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

To move image partly Im afraid that there is no easy way to do it. An alternate way would be by calculating the endPosition and a path based on sunset/sunrise so you don't have to mess things up with animation time at all

查看更多
登录 后发表回答