iOS 對當前webView進行截屏


UIWebView和WKWebView的截屏有所區別:

UIWebView:

func getImage(context: ServiceExecuteContext) -> UIImage {
        //創建一個基於位圖的圖形上下文並指定大小
        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該是屏幕的大小。其實了解了這個過程,就知道這個方法可以獲取任意區域的截圖,當然是必須當前頁面的一部分。你需要截取哪個view的圖像,就讓這個view的layer調用renderInContext把圖形渲染進當前圖形context。

 

 

 WKWebView:

    當我嘗試去截取WKWebView的圖。截圖的結果返回給我的就僅僅只是一張背景圖, 顯然截圖失敗。通過搜索StackOverflow和Google, 我發現WKWebView並不能簡單的使用layer.renderInContext的方法去繪制圖形。如果直接調用layer.renderInContext需要獲取對應的Context, 但是在WKWebView中執行UIGraphicsGetCurrentContext()的返回結果是nil

     StackOverflow提供了一種解決思路是使用UIViewdrawViewHierarchyInRect方法去截取屏幕視圖。通過直接調用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!
    }

  

http://blog.csdn.net/haoziy1989511/article/details/50856178

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM