Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 7 taking screenshot of part of a UIView

I have a view (testView) that is 400x320 and I need to take a screenshot of part of this view (say rect = (50, 50, 200, 200)). I am playing around with the drawViewHierarchy method in iOS 7 but I can't figure out how to do it correctly.

    UIGraphicsBeginImageContextWithOptions(self.testView.bounds.size, NO, [UIScreen mainScreen].scale);

    [self.testView drawViewHierarchyInRect:self.testView.bounds afterScreenUpdates:YES];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

Any help will be appreciated!

Thanks.

like image 552
user754905 Avatar asked Dec 13 '13 02:12

user754905


1 Answers

After getting the whole snapshot, you could draw it in a smaller Graphic Context in a way that you get the part you want:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), YES, [UIScreen mainScreen].scale);
[image drawInRect:CGRectMake(-50, -50, image.size.width, image.size.height)];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

EDIT: Better yet, draw the hierarchy directly in that smaller context:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), NO, [UIScreen mainScreen].scale);
[self.testView drawViewHierarchyInRect:CGRectMake(-50, -50, self.testView.bounds.size.width, self.testView.bounds.size.height) afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
like image 80
Rufel Avatar answered Nov 15 '22 00:11

Rufel