ios WKWebView 网页截长图

怎样截取网页长图,之前的 UIWebview 是可以用网上常用的方法,但是 WKWEbView 不能用了,截图之后只有当前显示的部分,其他部分都是空白,没有渲染上。求解,好人一生平安!!!

阅读 6.4k
2 个回答

WKWebView 你试试我写的代码, 原来使用 swift 2 写的.

func convertWholePageToImage() -> UIImage{
    let boundsWidth = webView.bounds.width
    let boundsHeight = webView.bounds.height
    let scrollView = self.webView.scrollView
    let oldOffset = scrollView.contentOffset
    scrollView.setContentOffset(CGPointZero, animated: false)
    var contentHeight = scrollView.contentSize.height
    //        let screenHeight = self.webview.bounds.height
    let scale = UIScreen.mainScreen().scale
    
    var images:[UIImage] = []
    while contentHeight > 0{
      UIGraphicsBeginImageContextWithOptions(webView.bounds.size, false, scale)
      webView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
      let image = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
      images.append(image)
      
      let offsetY = scrollView.contentOffset.y
      scrollView.setContentOffset(CGPoint(x: 0, y: offsetY + boundsHeight), animated: false)
      contentHeight = contentHeight - boundsHeight
    }
    scrollView.setContentOffset(oldOffset, animated: false)
    
    // concate the page
    UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, false, scale)
    for (index,image) in images.enumerate(){
      image.drawInRect(CGRect(x: CGFloat(0), y: boundsHeight * CGFloat(index), width: boundsWidth, height: boundsHeight ))
    }
    let fullImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return fullImage
  }
新手上路,请多包涵
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题