Reputation: 47348
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
How can I take a screenshot of UIView
using a rectangle that is rotated arbitrarily?
//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);
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.
Upvotes: 4
Views: 1133
Reputation: 242
Here's the code required to crop an image based on a simple rectangle.
I'm not sure how you're tracking your rectangle's rotation, but it should be pretty straight forward from there to apply this solution;
// Create rectangle from middle of current image
CGRect croprect = CGRectMake(image.size.width / 4, image.size.height / 4 ,
(image.size.width / 2), (image.size.height / 2));
// Draw new image in current graphics context
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], croprect);
// Create new cropped UIImage
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
Hope it helps.
Upvotes: 1