title: Swift rotating portrait image without scale
body: <p>I have a problem with swift, I have an app that, when a button is pressed, must rotate an image of 90°, for doing this I use this code</p>
  
  <pre><code>extension UIImage {
  public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -&gt; UIImage {
      let radiansToDegrees: (CGFloat) -&gt; CGFloat = {
          return $0 * (180.0 / CGFloat(M_PI))
      }
      let degreesToRadians: (CGFloat) -&gt; CGFloat = {
          return $0 / 180.0 * CGFloat(M_PI)
      }
  
      // calculate the size of the rotated view's containing box for our drawing space
      let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size))
      let t = CGAffineTransformMakeRotation(degreesToRadians(degrees));
      rotatedViewBox.transform = t
      let rotatedSize = rotatedViewBox.frame.size
  
      // Create the bitmap context
      UIGraphicsBeginImageContext(rotatedSize)
      let bitmap = UIGraphicsGetCurrentContext()
  
      // Move the origin to the middle of the image so we will rotate and scale around the center.
      CGContextTranslateCTM(bitmap, 0.5 * rotatedSize.width, 0.5 * rotatedSize.height);
  
      //   // Rotate the image context
      CGContextRotateCTM(bitmap, degreesToRadians(degrees));
  
      // Now, draw the rotated/scaled image into the context
      var yFlip: CGFloat
  
      if(flip){
          yFlip = CGFloat(-1.0)
      } else {
          yFlip = CGFloat(1.0)
      }
  
      CGContextScaleCTM(bitmap, yFlip, -1.0)
      CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)
  
      let newImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
  
      return newImage
  }}
  </code></pre>
  
  <p>with pictures in landscape i haven't any problem but when I try to rotate an image in portrait, on the first press of the button the image is scaled adapting its width to the width of the ImageView, losing his proportions, and without rotate, it is rotated, always with new proportions, only with the second pressure... can anyone help me?</p>
  
  <p>here a screenshot of the starting situation
  <a href="https://i.stack.imgur.com/d2CYZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d2CYZ.jpg" alt="enter image description here"></a></p>
  
  <p>after first press
  <a href="https://i.stack.imgur.com/quRBY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/quRBY.jpg" alt="enter image description here"></a></p>
  
  <p>after second press<a href="https://i.stack.imgur.com/Hwuix.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hwuix.jpg" alt="enter image description here"></a></p>