WKWeb查看内容

WKWebView content

我正在使用 WKWebView()。我的 webView 高度的大小 = 100。 我正在 WKWebview 中加载一个 .gif 图像。 gif图片的大小height = 300。我想把webview里面的图片压缩到里面。

如下图所示,图片没有缩小到 webView 大小,它的原始大小是 300

如果我把 6 个 WkWebview 给 300,它就合适了 .

我试过给予

    self.webView.contentMode = .scaleAspectFit
    self.webView.sizeToFit()
    self.webView.autoresizesSubviews = true

    self.webView.scrollView.contentInset = UIEdgeInsetsMake(0,0,0,0)
    self.webView.scrollView.isScrollEnabled = false

这是我添加 WKWebview 的方式:

self.webView = WKWebView() 
self.webView.frame = CGRect.init(x: 0, y: 64, width: self.view.frame.width, height:200) 
self.webView.autoresizingMask = .flexibleWidth 
let heightConstraint = NSLayoutConstraint(item: self.webView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)
self.view.addSubview(self.webView) 
let filePath = Bundle.main.path(forResource:"token", ofType: "gif")
let gifData = NSData(contentsOfFile: filePath!) 
self.webView.load(gifData as! Data, mimeType: "image/gif", characterEncodingName: String(), baseURL: NSURL() as URL)

根据 Web 视图的配置,您可以:

  1. 设置 img 标签的样式,使其填充网络视图的高度:

    let htmlContent = "<img src=\"token.gif\" style=\"margin: auto; height: 100%\" />"
    
  2. 或对其高度进行硬编码:

    let htmlContent = <img src=\"token.gif\" style=\"margin: auto; height: 300px\" />"
    

    或者,您可以使用字符串插值常量代替硬编码值

    let htmlContent = "<img src=\"token.gif\" style=\"margin: auto; height: \(webViewHeight)px\" />"
    

然后您可以将 html 加载到网络视图:

webView.loadHTMLString(htmlContent, baseURL: Bundle.main.bundleURL)

要加快 Web 视图的速度,您可以内联图像数据而不是引用 gif 文件 - 有关此主题的更多信息,请参阅 Embedding Base64 Images