Rotate UIView around its center keeping its size

前端 未结 10 1109
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 14:17

I\'m trying to rotate an UIView a few radians but after applying the transformation it doesn\'t look to be keeping its size. What\'s the proper way to achieve t

相关标签:
10条回答
  • 2020-12-02 14:50

    You're probably hitting a problem with Autolayout. You probably have constraints on the rotated view pinning it to the edges of the superview. When the transform is applied, Autolayout is updating the view's size to still fit within the superview.

    You can experiment with different constraints (e.g. pinning the centre of the view to the centre of another view, and pinning the width and height to constant values) or turn Autolayout off for the rotated view, or, if these don't work or don't suit your needs, use a container view which is laid out under Autolayout, and add your rotating view to this, without using Autolayout.

    This can only be done in code - you can make individual views subject to Autolayout or not by setting translatesAutoresizingMasksIntoConstraints to NO (Autolayout on) or YES (Autolayout off). You'll need to set the appropriate autoresizing masks if you switch a view from one to the other.

    0 讨论(0)
  • 2020-12-02 14:51

    Swift5

    Rotate UIView Upside down

    let degrees:CGFloat = -180 //angle to convert upside down
    rotatingUI.transform = CGAffineTransform(rotationAngle: degrees * CGFloat(Double.pi)/180);
        
    
    0 讨论(0)
  • 2020-12-02 14:52

    Swift 5:

    extension UIView {
        func setTransformRotation(toDegrees angleInDegrees: CGFloat) {
            let angleInRadians = angleInDegrees / 180.0 * CGFloat.pi
            let rotation = self.transform.rotated(by: angleInRadians)
            self.transform = rotation
        }
    }
    
    0 讨论(0)
  • 2020-12-02 14:55

    Try with this code:

    #define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
    
    double rads = DEGREES_TO_RADIANS(240);
    self.arrowView.layer.transform = CATransform3DMakeRotation(rads, 0, 0, 1);
    
    0 讨论(0)
提交回复
热议问题