How to capture a specific size of the self.view

旧城冷巷雨未停 提交于 2019-12-13 04:02:02

问题


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!


回答1:


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();


来源:https://stackoverflow.com/questions/12692611/how-to-capture-a-specific-size-of-the-self-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!