Put object along the path and then move it (IMG IN

2019-06-27 02:24发布

I have a problem ( ;) ) and I need your help.

Lets look at the image:

problem visual explanation

1) I have a path. Lets say it's like this:

let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(10.5, 47.5))
bezierPath.addCurveToPoint(CGPointMake(45.5, 23.5), controlPoint1: CGPointMake(10.5, 47.5), controlPoint2: CGPointMake(32.5, 23.5))
bezierPath.addCurveToPoint(CGPointMake(84.5, 47.5), controlPoint1: CGPointMake(58.5, 23.5), controlPoint2: CGPointMake(84.5, 47.5))
bezierPath.addLineToPoint(CGPointMake(10.5, 47.5))
bezierPath.closePath()
UIColor.redColor().setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()

2) I have an UIImageView. First question is: How to put it on the top of specified part of the path (A point) ?

3) Second question: How to animate it from point A to B ?

1条回答
Lonely孤独者°
2楼-- · 2019-06-27 02:53

By using CAKeyframeAnimation, you can create an animation using the path you made

let animation = CAKeyframeAnimation()

// Could also be position.x or position.y if you want to animate a separate axis.
animation.keyPath = "position"
animation.repeatCount = 0 // How many times to repeat the animation
animation.duration = 5.0 // Duration of a single repetition

animation.path = bezierPath.CGPath

and then attach it to your image's layer

imageView.layer.addAnimation(animation, forKey: "move image along bezier path")

This other stackoverflow question helped me form this answer, and if all else fails, you could always refer to the docs.

查看更多
登录 后发表回答