0
votes

let's assume i have created a custom UIView like that:

let view = CustomView((frame: CGRect(x: 0, y: 44, width: self.view.frame.width, height: self.view.frame.width))
                                           ======

and I want to rotate it that way:

// Inside the CustomView    
self.transform = CGAffineTransform(rotationAngle: angle)

Then the view is not rotating around its center. But if the view is created like this

let view = CustomView((frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.width))
                                           =====

(I have marked the difference with =====)

the view is rotating around its center as expected. I understand that the rotation center can be adjusted via anchorpoint. But as far as I understand CGPoint(0,0) means "upper left corner", CGPoint(0.5, 0,5) means center, but this does not work if the y axis of the origin is diffrent from 0.

Can anyone tell me how to solve this?

1

1 Answers

0
votes

To set the anchorPoint use the following method

func setAnchorPoint(_ anchorPoint: CGPoint, for view: UIView) {
    var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y)
    var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y)

    newPoint = newPoint.applying(view.transform)
    oldPoint = oldPoint.applying(view.transform)

    var position: CGPoint = view.layer.position
    position.x -= oldPoint.x
    position.x += newPoint.x
    position.y -= oldPoint.y
    position.y += newPoint.y

    view.layer.position = position
    view.layer.anchorPoint = anchorPoint
}

you can set anchor point like...

setAnchorPoint(CGPoint(x: 0.5, y: 0.5), view: view)

And after that perform transformation. So it will transform view around its anchor point.