ytpm
ytpm

Reputation: 5150

How to capture a specific size of the self.view

I have the self.view, but I only want to capture 300x320 of it.

got this code:

UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

UIImage * imgPrintScreen = [[UIImage alloc]init];
imgPrintScreen = viewImage;

What do I need to change here in order to do so?

Thanks allot!

Upvotes: 0

Views: 150

Answers (1)

Jason Coco
Jason Coco

Reputation: 78393

Just change the size that you want to capture, instead of using the entire bounds, use the size you want. The render will start at the origin of the view and be clipped when it falls outside the bounds. If you need to change where the view is actually clipped, simply translate the context after starting the image context:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 320), YES, 0.);
[self.view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

If your view was, for example, 600x320 and you wanted to capture the middle 300 points in width, you'd translate the context 150 points to the left:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 320), YES, 0.);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, -150.f, 0.f);
[self.view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Upvotes: 2

Related Questions