lp.jpg
開發中如何截圖,webView為例,用法如下:
(一)截取當前屏幕顯示的區域(設備的全屏)
代碼如下:
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); //保存到相冊中
(二)截取webView所有顯示內容的區域
客戶提出相關需求,需要截圖當前webview所展示的所有的內容,代碼如下:
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); //設置截屏大小
[scroll.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef imageRef = viewImage.CGImage;
UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRef];
UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);//保存圖片到照片庫
// 恢復frame 不然滑動沒效果
scroll.frame = frame1;
解釋:
1、初始沒有截圖的時候,如果UIScrollView的高度不等于webView.scrollView.contentSize.height,后期截圖的結果就是圖片的高度是對的,但是只有只有當前屏幕展示的內容,其他展示不到的都是黑屏。
2、截圖修改了frame的高度,截圖完畢之后如果不恢復之前的高度,是看不到滑動效果的,因為UIScrollView高度大于你的設備的屏幕高。
注意:
為避免內存泄漏,UIGraphicsBeginImageContextWithOptions
與UIGraphicsEndImageContext
需成對出現。
資料:
UIGraphicsBeginImageContext 和 UIGraphicsBeginImageContextWithOptions