Swift-如何使动画箭头指向正确的方向?

时间:2019-01-08 02:44:14

标签: swift xcode animation uibezierpath cashapelayer

我有两个按钮,当它们连接时,显示一条带有动画箭头的线以表明它们已连接。问题是当动画激活时,箭头自身没有正确旋转以指向正确的方向。

在移动时如何旋转箭头指向正确的方向?

class ViewController: UIViewController {

let line = CAShapeLayer()
let linePath = UIBezierPath()

var triangleImage = UIImage(named: "triangle" )
let startCoordinate = CGRect(x: 100, y: 100, width: 0, height: 0)

let btn1 = UIButton()
let btn2 = UIButton()

override func viewDidLoad() {
    super.viewDidLoad()

    btn1.createRectangleButton(buttonPositionX: 100, buttonPositionY: 100, buttonWidth: 80, buttonHeight: 40, buttonTitle: "", buttonTag: 0)
    btn2.createRectangleButton(buttonPositionX: 300, buttonPositionY: 400, buttonWidth: 80, buttonHeight: 40, buttonTitle: "", buttonTag: 1)

    view.addSubview(btn1)
    view.addSubview(btn2)


    let imageView = UIImageView(image: triangleImage)
    imageView.frame = CGRect(x:100, y:100, width: 20, height: 20)
    imageView.center = self.btn1.center
    view.addSubview(imageView)

    linePath.move(to: btn1.center)
    linePath.addLine(to: btn2.center)
    line.path = linePath.cgPath
    line.strokeColor = UIColor.red.cgColor
    self.view.layer.addSublayer(line)


    view.bringSubviewToFront(imageView)

    UIView.animate(withDuration: 3, delay: 0.0, options: [.repeat, .curveLinear], animations: {
        imageView.center = self.btn2.center
    }, completion: nil)
}

enter image description here

请注意:上面的代码看上去与图片略有不同

1 个答案:

答案 0 :(得分:1)

尝试此轮换变换

// rotation
imageView.transform = CGAffineTransform(rotationAngle: atan2(btn2.center.y - btn1.center.y, btn2.center.x - btn1.center.x) + CGFloat.pi / 2)
// used triangle image below

enter image description here