2
votes

I'm having a ruler (red) and a UIView (orange) below it like this:

enter image description here

When I rotate the ruler, the UIView rotates as well but it's location is not what I expected:

enter image description here

I use UILongPressGestureRecognizer to rotate the ruler, when I hold finger and move, I got an angle to re-draw the ruler and it worked perfectly but not for the UIView.

How I create and rotate the UIView:

 func createUIViewOutSideRuler(touchedPoint:CGPoint, notTouchedPoint:CGPoint, angle: CGFloat) -> UIView{
        let viewWidth = distanceFromTwoPoints(touchedPoint, notTouchedPoint)

        let view = UIView(frame: CGRect(x:notTouchedPoint.x, y: notTouchedPoint.y , width:  viewWidth, height: dotLineSize * 2))
        
        view.transform = CGAffineTransform(rotationAngle: angle);

        view.backgroundColor = .orange
        self.addSubview(view)
        return view
    }

Update base on Sweeper comment

let view = UIView(frame: CGRect(x:notTouchedPoint.x, y: notTouchedPoint.y , width:  viewWidth, height: dotLineSize * 2))
        
let vectorToStartPoint = CGPoint(x: view.center.x - touchedPoint.x,
                                         y: view.center.y - touchedPoint.y )
view.transform = CGAffineTransform(translationX: vectorToStartPoint.x, y: vectorToStartPoint.y)
                             .rotated(by: angle)
                             .translatedBy(x: -vectorToStartPoint.x, y: -vectorToStartPoint.y)

Result:

Note: I drag the touchedPoint to rotate

Center around touchedPoint enter image description here

Center around notTouchedPoint enter image description here

1

1 Answers

2
votes

You need to rotate the view around notTouchedPoint. By default, a rotation created with CGAffineTransform.init(rotationAngle:) will rotate the view around its centre.

To do this, first translate the centre of the view to startPoint, rotate it, then translate it back.

let vectorToNotTouchedPoint = CGPoint(x: view.center.x - notTouchedPoint.x
                                      y: view.center.y - notTouchedPoint.y)
view.transform = CGAffineTransform(translationX: vectorToNotTouchedPoint.x, y: vectorToNotTouchedPoint.y)
                     .rotated(by: angle)
                     .translatedBy(x: -vectorToNotTouchedPoint.x, y: -vectorToNotTouchedPoint.y)