20

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.

2 Answers 2

37

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

In Swift with self.hostView.superview!.drawHierarchy(in: frame, afterScreenUpdates: true) where frame is for sure smaller than the superView, I still get the complete view's content. But it's condensed to the CGSize I supplied to UIGraphicsBeginImageContextWithOptions() (which I of course made the same as my frame's size).
@meaning-matters the trick here is to draw the hierarchy by using the exact same size of your view (to prevent scaling), and offset it to get the part you want. By using UIGraphicsBeginImageContextWithOptions(CGSize(width: 200, height: 200), true, 0) you could get the top-left 200x200 part of your view with view.drawHierarchy(in: view.bounds, afterScreenUpdates: true). You could also offset the part your get this way: view.drawHierarchy(in: UIEdgeInsetsInsetRect(view.bounds, UIEdgeInsets(top: -100, left: -100, bottom: 0, right: 0)), afterScreenUpdates: true). Hope it helps!
0

Try below line of code,

UIView *popSnapshot=[inputView snapshotViewAfterScreenUpdates:YES]; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.