Alwin Vazhappilly
Alwin Vazhappilly

Reputation: 1514

How to rotate UIVIew in its top left coordinates?

Existing CGAffineTransform performs this job well, But it only rotates in its center points. I want to rotate the UIView in its Top-Left coordinates,

Rotation Code:

// here rectangle is UIView
rectangle.transform = CGAffineTransform(rotationAngle: 90.degreesToRadians)

Extension:

// use to convert degree to radian
extension BinaryInteger {
    var degreesToRadians: CGFloat { return CGFloat(Int(self)) * .pi / 180 }
}

I cant find my answer in suggested question.

Upvotes: 0

Views: 1821

Answers (2)

Alwin Vazhappilly
Alwin Vazhappilly

Reputation: 1514

Thanks Here Trix and the4kman for the idea. I solved my problem. Here Trix answer not fully helped me. But He shows some hints. Using that hints I solved my answer.

Step 1

Create this extension for UIView to set anchorPoint

extension UIView{
    func setAnchorPoint(anchorPoint: CGPoint) {

        var newPoint = CGPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y)
        var oldPoint = CGPoint(x: self.bounds.size.width * self.layer.anchorPoint.x, y: self.bounds.size.height * self.layer.anchorPoint.y)

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

        var position : CGPoint = self.layer.position

        position.x -= oldPoint.x
        position.x += newPoint.x;

        position.y -= oldPoint.y;
        position.y += newPoint.y;

        self.layer.position = position;
        self.layer.anchorPoint = anchorPoint;
    }
}

Usage

rectangle.setAnchorPoint(anchorPoint: CGPoint.zero)
rectangle.transform = CGAffineTransform(rotationAngle: 90.degreesToRadians)

This working perfectly.

Upvotes: 0

HereTrix
HereTrix

Reputation: 1417

Just change anchorPoint of layer before transformation. For example:

rectangle.layer.anchorPoint = CGPoint.zero
rectangle.transform = CGAffineTransform(rotationAngle: 90.degreesToRadians)

Upvotes: 2

Related Questions