title: iPhone iOS how to take a screenshot programmatically with rotation?
body: <p>I know how to take a regular rectangular screenshots of the iPhone/iPad screen (code below). However, I'm looking for a way to get a screenshot that is rotated by an arbitrary number of degrees</p>
  
  <p><strong>How can I take a screenshot of <code>UIView</code> using a rectangle that is rotated arbitrarily?</strong></p>
  
  <pre><code>    //this is the rotation of the rectangle
          NSNumber* savedRotation = [NSNumber numberWithFloat: 0.35]; //radians, get the real number from a gesture recognizer
  
          //create a screenshot
          CGSize screenshotSize;
  
  //screenshot size has to be adjusted for the rotation, or multiplied by the square root of 2
          if( UIDeviceOrientationIsLandscape([[UIApplication sharedApplication]statusBarOrientation]))
          {
              screenshotSize  =  CGSizeMake(1024,768);
          }else
          {
              screenshotSize  =  CGSizeMake(768, 1024);
  
          }
  
          if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
              UIGraphicsBeginImageContextWithOptions(screenshotSize, NO, [UIScreen mainScreen].scale);
  
  
          else
              UIGraphicsBeginImageContext(screenshotSize);
  
          CGContextRef context = UIGraphicsGetCurrentContext();
          CGContextSaveGState(context);
  
      //this does the proper rotation, but there's some kind of extra translation required to make it capture what's under the rectangle
          CGContextRotateCTM(context, -savedRotation.floatValue);
          [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
  
  
          UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
  
          CGContextRestoreGState(context);
  </code></pre>
  
  <p>Here's the result of the code above, it seems to partially work, but requires some extra translation of the CTM to perfectly match the capture rectangle. Additionally, I need to change the bounds of the context to be wider ( probably 1024 * sqrt(2) width and height) to allow for any rotation without clipping.</p>
  
  <p><img src="https://i.stack.imgur.com/JqTtO.jpg" alt="enter image description here"></p>