UIView animation determine center during animation

前端 未结 2 1008
滥情空心
滥情空心 2021-01-24 23:22

I\'m using UIView\'s + animateWithDuration:delay:options:animations:completion: method to move my view along a line over the course of a few seconds or so.

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-25 00:10

    I know its too late but maybe it can help somebody else.

    CALayer has a presentation() function

    func presentation() Returns a copy of the presentation layer object that represents the state of the layer as it currently appears onscreen.

    the presentation layer has a frame property what is a CGRect and from here easy the calculate the midpoint.

    Demo

    The code in swift 3

    class ViewController: UIViewController {
            var circle : UIView!
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            let animator = UIViewPropertyAnimator(duration: 10, curve: .easeInOut)
            circle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0))
            circle.layer.cornerRadius = 20.0
            circle.backgroundColor = UIColor.blue
            self.view.addSubview(circle)
            Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true)
            {
                [weak self] (myTimer) -> Void in
                if let movingBlueDotFrame = self?.circle.layer.presentation()?.frame
                {
                    let blueDotOriginPoint = movingBlueDotFrame.origin
                    let blueDotMiddlePoint = CGPoint(x: blueDotOriginPoint.x + movingBlueDotFrame.width/2, y: blueDotOriginPoint.y + movingBlueDotFrame.height/2)
                    print(blueDotMiddlePoint)
                    if blueDotMiddlePoint == CGPoint(x:100,y:100){
                        print("Yeeaahh")
                        myTimer.invalidate()
                    }
                }
           }
            animator.addAnimations {
                self.circle.center = CGPoint(x: 100,y: 100)
            }
            animator.startAnimation()
        }
    }
    

提交回复
热议问题