如何在UIWebView中仅调整图像大小?

6
我将包含文本和图片的HTML加载到了我的UIWebView中。
文字适合UIWebView,而图片不适合UIWebView。
它在UIWebView中太大了。
它在UIWebView的末尾显示滚动条。
我想调整图像适应UIWebView的大小。因此,我测试了以下代码。
self.myWebView.scalesPageToFit = YES;

然而,现在文本和文字太小无法读取,图片是固定的。

我希望将文本设置为正常大小,并且只想要适应 UIWebView 中的图片大小。

我该怎么做?


你解决了你的问题吗?我也有同样的问题? - Yestay Muratov
3个回答

10
我已使用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];

在添加了<style>img{max-width:100%%;height:auto !important;width:auto !important;};</style>代码后,它按预期工作,最大图像宽度小于或等于Web视图宽度。 - Tyson Vignesh

5

我正在使用HTML和NSString,像这样:<html><head><body>%@</body></head></html>。我应该把这些代码放在哪里? - Fire Fist
在<head>标签中添加以下内容:<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"> </head> <body> </body> - Rocker
1
是的,我按照你说的添加了,但它不起作用。 - Fire Fist

0

以下代码片段可能会对您有所帮助

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];

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接