1

I have two buttons which when connected, show a line with an animated arrow to show that they are connected.The issue is the arrow it self is not rotating appropriately to point in the right direction when animated.

How can I rotate the arrow to point in the right direction when moving?

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

note: the code above will look slightly different to the image

STerrier
  • 3,755
  • 1
  • 16
  • 41

1 Answers1

1

Try this rotation transformation

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

ChanOnly123
  • 1,004
  • 10
  • 12