Rendering a UIWebView into an ImageContext

前端 未结 6 1123
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 12:33

I am trying to capture the contents of a UIWebView including that which is not visible to the user. i.e. The whole web page even though the user is only looking at the top.<

6条回答
  •  感情败类
    2020-12-14 12:56

    I've released an app (Web2Pic) doing that, and please trust me that UIGraphicsBeginImageContext(webView.frame.size); can do nothing except getting a small image from the visible area in our UIWebView ;-(

    The right way is a bit complex but it just works:

    1.Use JavaScript in our UIWebView to get these float values:

       //Whole page size in HTML coordinate
       document.body.scrollWidth
       document.body.scrollHeight
       //UIWebView visible size in HTML coordinate
       window.innerWidth
       window.innerHeight
    

    2.Now we can 'cut' the whole page into dozens of UIWebView-sized small pieces. Then we can capture every small pieces individually and save them into our Cache. I implemented this by calculating page-offsets and use UIGraphicsBeginImageContext(webView.frame.size); to get a array of images. In addition, you should cache the image array into the file system, or the app will eventually crash!

    3.When we finally got all the small pieces, we can start a full-resolution context: UIGraphicsBeginImageContext(CGSizeMake(document.body.scrollWidth,document.body.scrollHeight));

    4.Render every small images into the big context based on the coordinates. And be careful to the corners, the last image in every line/row may not be a full image.

    5.There is still one step left: saving the big image. Do not save it into the PhotoAlbum, because iOS will automatically cut down the resolution of images in the album. Instead, we can save it into the file system and enable the app's iTunes File Share support, or even write a simple in-app photo manager.

    Hope these can help ;-)

    Yichao Peak Ji

提交回复
热议问题