
lp.jpg
開發(fā)中如何截圖,webView為例,用法如下:
(一)截取當(dāng)前屏幕顯示的區(qū)域(設(shè)備的全屏)
代碼如下:
CGSize size = self.view.frame.size;
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, self, nil, nil); //保存到相冊(cè)中
(二)截取webView所有顯示內(nèi)容的區(qū)域
客戶提出相關(guān)需求,需要截圖當(dāng)前webview所展示的所有的內(nèi)容,代碼如下:
UIScrollView *scroll = (UIScrollView *)_webView;
CGRect frame = scroll.frame;
CGRect frame1 = scroll.frame; // 備份frame
frame.size.height = _webView.scrollView.contentSize.height;
scroll.frame = frame;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(iChe_ViewFrame.size.width,frame.size.height), YES, 0); //設(shè)置截屏大小
[scroll.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef imageRef = viewImage.CGImage;
UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRef];
UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);//保存圖片到照片庫
// 恢復(fù)frame 不然滑動(dòng)沒效果
scroll.frame = frame1;
解釋:
1、初始沒有截圖的時(shí)候,如果UIScrollView的高度不等于webView.scrollView.contentSize.height,后期截圖的結(jié)果就是圖片的高度是對(duì)的,但是只有只有當(dāng)前屏幕展示的內(nèi)容,其他展示不到的都是黑屏。
2、截圖修改了frame的高度,截圖完畢之后如果不恢復(fù)之前的高度,是看不到滑動(dòng)效果的,因?yàn)閁IScrollView高度大于你的設(shè)備的屏幕高。
注意:
為避免內(nèi)存泄漏,UIGraphicsBeginImageContextWithOptions與UIGraphicsEndImageContext需成對(duì)出現(xiàn)。
資料:
UIGraphicsBeginImageContext 和 UIGraphicsBeginImageContextWithOptions