【问题标题】:How to make fit size only for Image in UIWebView?如何只为 UIWebView 中的图像制作合适的尺寸?
【发布时间】:2026-01-09 20:50:01
【问题描述】:

我将HTML 加载到我的UIWebView 中,包括TextImages

Text 适合 UIWebViewImages 不适合 UIWebView

UIWebView 太大了。

它在UIWebView 的末尾显示滚动条。

我想在 UWebView 中调整图像适合大小。所以我用以下代码进行了测试。

self.myWebView.scalesPageToFit = YES;

但是它是固定的,包括文本和文本太小无法阅读并且图像是固定的。

我想正常设置文本,只想在UIWeView 中调整大小图像。

我该怎么做?

【问题讨论】:

  • 你的问题解决了吗?我也有同样的问题?

标签: html ios image uiwebview


【解决方案1】:

我已经使用 css 解决了这个问题。下面样式标签中包含的 css 将确保自动调整图像大小,保持 UIWebView 宽度的纵横比。希望这会有所帮助!

NSString *strTemplateHTML = [NSString stringWithFormat:@"<html><head><style>img{max-width:100%%;height:auto !important;width:auto !important;};</style></head><body style='margin:0; padding:0;'>%@</body></html>", @"insert your html content here"];

[webView loadHTMLString:strTemplateHTML baseURL:nil];

【讨论】:

  • 它按预期工作,添加&lt;style&gt;img{max-width:100%%;height:auto !important;width:auto !important;};&lt;/style&gt;代码后最大图像宽度小于或等于webview宽度
【解决方案2】:

iPhone/iPad 上的 UIWebView 使用 viewport 元标记来确定如何显示网页。

 <meta name="viewport" content="width=device-width, maximum-scale=1.0" />

更多详情请参考以下链接:

https://developer.apple.com/library/ios/DOCUMENTATION/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html

【讨论】:

  • 我正在使用带有 NSString 的 HTML,例如 %@。我把这些代码放在哪里?
  • 添加head标签
【解决方案3】:

下面的代码sn-p可能对你有帮助

NSString *fontString = @"<!DOCTYPE html><html>\
    <head>\
    <style>\
    img{";
        NSString *imageDimensionsStr = [NSString stringWithFormat:@"max-width: %fpx; max-height: %fpx;}",self.view.frame.size.width - 50.0f, self.view.frame.size.height/2];
        fontString =[fontString stringByAppendingString:imageDimensionsStr];
fontString = [fontString stringByAppendingString:@"</style></head><body>"];
    fontString = [[fontString stringByAppendingString:htmlString] stringByAppendingString:@"</body></html>"];
    [webView loadHTMLString:fontString baseURL:nil];

以上代码将根据视图尺寸调整图像的宽度和高度。您可以根据自己的要求进行更改。

【讨论】:

    最近更新 更多