有时候我们需要用webView加载一些html网页来展示某些业务内容,但是有时候网页里的图片总是不能按照屏幕尺寸进行显示,往往由于网页图片过大导致浏览效果极差。因此要么给出适配好的内容文件,要么只能前端去处理了。
由此记下处理办法,以免以后遇到相同的问题及时去处理。
准备一个html文件,带有图片(图片尺寸明显大于手机屏幕),html文件代码如下:
<html>
<head></head>
<meta charset='UTF-8'>
<body>
<h1>图片自适应 (萌)</h1>
</img>
<h2>图片自适应 (美女)</h2>
</img>
<h2>图片自适应 (初音)</h2>
</img>
<h2>图片自适应 (鼬神)</h2>
</img>
<h2>图片自适应 (卡殿)</h2>
</img>
<h2>图片自适应 (美少女)</h2>
</img>
<h2>图片自适应 (穹妹)</h2>
</img>
<h2>图片自适应 (O(∩_∩)O哈哈~)</h2>
</img>
</body>
</html>
初始化webView,加载html文件:
UIWebView * webView = [UIWebView new];
webView.delegate = self;
[self.view addSubview:webView];
webView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(64, 0, 0, 0));
NSString * path = [[NSBundle mainBundle] pathForResource:@"text.html" ofType:nil];
NSURL * url = [NSURL URLWithString:path];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
再不做处理时加载完的样子是这样的:

接下来在webView加载完成的代理方法里做下处理:
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *jsStr = @"function reSetImgFrame() { \
var imgs = document.getElementsByTagName('img'); \
for (var i = 0; i < imgs.length; i++) {\
var img = imgs[i]; \
img.style.maxWidth = %f; \
} \
}";
jsStr = [NSString stringWithFormat:jsStr, [UIScreen mainScreen].bounds.size.width - 20];
[webView stringByEvaluatingJavaScriptFromString:jsStr];
[webView stringByEvaluatingJavaScriptFromString:@"reSetImgFrame()"];
}
处理完的效果是这样的:

好了,我们的效果达到了,收工!
参考文章:标哥的技术博客
网友评论