iOS 對當前webView進行截屏的方法
UIWebView和WKWebView的截屏有所區(qū)別:
UIWebView:
func getImage(context: ServiceExecuteContext) -> UIImage { //創(chuàng)建一個基于位圖的圖形上下文并指定大小 UIGraphicsBeginImageContextWithOptions(context.fromViewController.webView.bounds.size, true, 0) //renderInContext呈現接受者及其子范圍到指定的上下文 context.fromViewController.webView.layer.renderInContext(UIGraphicsGetCurrentContext()!) //返回一個基于當前圖形上下文的圖片 let image = UIGraphicsGetImageFromCurrentImageContext() //移除棧頂的基于當前位圖的圖形上下文 UIGraphicsEndImageContext() //let imagRef = CGImageCreateWithImageInRect((image?.CGImage)!, context.fromViewController.webView.bounds) //let newImage = UIImage.init(CGImage: imagRef!) //UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil);//保存圖片到照片庫 return image! }
UIGraphicsBeginImageContext()方法傳入唯一參數,是一個CGSize變量,用來指定圖形context的大小,所以獲取屏幕截圖的時候這個size該是屏幕的大小。其實了解了這個過程,就知道這個方法可以獲取任意區(qū)域的截圖,當然是必須當前頁面的一部分。你需要截取哪個view的圖像,就讓這個view的layer調用renderInContext把圖形渲染進當前圖形context。
WKWebView:
當我嘗試去截取WKWebView的圖。截圖的結果返回給我的就僅僅只是一張背景圖, 顯然截圖失敗。通過搜索StackOverflow和Google, 我發(fā)現WKWebView并不能簡單的使用layer.renderInContext的方法去繪制圖形。如果直接調用layer.renderInContext需要獲取對應的Context, 但是在WKWebView中執(zhí)行UIGraphicsGetCurrentContext()的返回結果是nil
StackOverflow提供了一種解決思路是使用UIView的drawViewHierarchyInRect方法去截取屏幕視圖。通過直接調用WKWebView的drawViewHierarchyInRect方法(afterScreenUpdates參數必須為true), 可以成功的截取WKWebView的屏幕內容
func getImage(context: ServiceExecuteContext) -> UIImage { UIGraphicsBeginImageContextWithOptions(context.fromViewController.webView.bounds.size, true, 0) for subView: UIView in context.fromViewController.webView.subviews { subView.drawViewHierarchyInRect(subView.bounds, afterScreenUpdates: true) } //UIApplication.sharedApplication().keyWindow?.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() //let imagRef = CGImageCreateWithImageInRect((image?.CGImage)!, context.fromViewController.webView.bounds) //let newImage = UIImage.init(CGImage: imagRef!) return image! }
以上這篇iOS 對當前webView進行截屏的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
iOS開發(fā)實現搜索框(UISearchController)
這篇文章主要為大家詳細介紹了iOS開發(fā)實現搜索框,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-08-08iOS應用開發(fā)中使用Auto Layout來適配不同屏幕尺寸
這篇文章主要介紹了iOS應用開發(fā)中使用Auto Layout來適配不同屏幕尺寸的方法,根據Xcode IDE下的實際調試步驟講解其用法,需要的朋友可以參考下2016-03-03iOS tableView右側索引視圖狀態(tài)獲取的方法實例
tableView用于顯示一個垂直滾動的單元格數(通常為可重復使用的單元格)組成的視圖,這篇文章主要給大家介紹了關于iOS tableView右側索引視圖狀態(tài)獲取的相關資料,需要的朋友可以參考下2021-07-07Objective-C中使用NSString類操作字符串的方法小結
這篇文章主要介紹了Objective-C中使用NSString類操作字符串的方法小結,文中講到了字符串的分割和拼接等一些常見的用法,需要的朋友可以參考下2016-01-01