【问题标题】:WKWebView takeSnapshot without scrollbars macOSWKWebView takeSnapshot 没有滚动条 macOS
【发布时间】:2020-12-06 05:04:02
【问题描述】:

尝试使用 WKWebView 渲染 SVG 文件。但是,滚动条显示在生成的快照中。 根据 WebKit implementation 有一个私有方法 _setMinimumLayoutWidth: 将禁用文档的可滚动性。该解决方案有效,但它是私有方法。

寻找一种不带滚动条的快照方式

PS:旧的 WebView 没有这个问题,因为我可以很容易地修改 scrollView。 10.16 有 createPDF,背景和滚动条都没有问题

  override init() {
    webView = WKWebView(frame: .zero)
    //webView.setValue(false, forKey: "alwaysShowsVerticalScroller") //doesn't work + private
    //webView.setValue(false, forKey: "alwaysShowsHorizontalScroller") //doesn't work + private
    //webView.perform(selector, with: NSNumber(value: 500.0))
    webView.setValue(500.0, forKey: "minimumLayoutWidth") //works but private
    webView.setValue(false, forKey: "draws" + "background".capitalized) //works but private
    super.init()
    webView.navigationDelegate = self
 }

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  
  //...some code to resize 
  webView.setFrameSize(NSMakeSize(svgNodeWidth * zoomFactor + offset , svgNodeHeight * zoomFactor + offset))

  let configuration = WKSnapshotConfiguration()
  webView.takeSnapshot(with: configuration) { (image, error) in

      //resulting image will show empty area for horizontal and vertical scrollbar
      if let error = error {
          debugPrint(error)
      }
      self.completion?(image)
    }
}

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="10" height="10" fill="purple" xmlns="http://www.w3.org/2000/svg">
  <!-- With a width of 0 or less, nothing will be rendered -->
  <rect x="0" y="0" width="10" height="10" fill="purple"/>
</svg>

【问题讨论】:

    标签: macos svg wkwebview


    【解决方案1】:

    问题仅出现在 macOS ~10.15.3 上。它在 10.13/10.14/11.0 上不存在。额外的填充将解决问题。

    let padding : CGFloat = 50
    
    func adjustSizeAndMagnify() {
        if svgNodeWidth > 0 && svgNodeHeight > 0 {
             zoomFactor = [minimumWidth / svgNodeWidth, minimumHeight / svgNodeHeight].max() ?? 1
             let backingScale = NSScreen.main?.backingScaleFactor ?? 1
             zoomFactor = zoomFactor / backingScale
             webView.setFrameSize(NSMakeSize(svgNodeWidth * zoomFactor + padding , svgNodeHeight * zoomFactor + padding))
             webView.magnification = zoomFactor
         }
    }
    
    func takeSnapshot() {
        adjustSizeAndMagnify()
        let configuration = WKSnapshotConfiguration()
        configuration.rect = NSMakeRect(0, 0, webView.frame.size.width - padding, webView.frame.size.height - padding)
        webView.takeSnapshot(with: configuration) { (image, error) in
            if let error = error {
                debugPrint(error)
            }
            self.completion?(image)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 2015-12-08
      相关资源
      最近更新 更多