有时候我们需要用webView加载一些html网页来展示某些业务内容,但是有时候网页里的图片总是不能按照屏幕尺寸进行显示,往往由于网页图片过大导致浏览效果极差。因此要么给出适配好的内容文件,要么只能前端去处理了。
由此记下处理办法,以免以后遇到相同的问题及时去处理。
准备一个html文件,带有图片(图片尺寸明显大于手机屏幕),html文件代码如下:
<html>
<head></head>
<meta charset='UTF-8'>
<body>
<h1>图片自适应 (萌)</h1>
![](http://upload-images.jianshu.io/upload_images/1350326-248f797db0ae9afe.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</img>
<h2>图片自适应 (美女)</h2>
![](http://upload-images.jianshu.io/upload_images/1350326-d81850f7ef08c360.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</img>
<h2>图片自适应 (初音)</h2>
![](http://upload-images.jianshu.io/upload_images/1350326-db46c3c791ff3a0d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</img>
<h2>图片自适应 (鼬神)</h2>
![](http://upload-images.jianshu.io/upload_images/1350326-52d4afc93d31140d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</img>
<h2>图片自适应 (卡殿)</h2>
![](http://upload-images.jianshu.io/upload_images/1350326-05e198ac280d1966.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</img>
<h2>图片自适应 (美少女)</h2>
![](http://img1.imgtn.bdimg.com/it/u=44603310,796842853&fm=21&gp=0.jpg)</img>
<h2>图片自适应 (穹妹)</h2>
![](http://upload-images.jianshu.io/upload_images/1350326-27ea1e5bb749a771.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</img>
<h2>图片自适应 (O(∩_∩)O哈哈~)</h2>
![](http://upload-images.jianshu.io/upload_images/1350326-2ad73139148bc49e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</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()"];
}
处理完的效果是这样的:
好了,我们的效果达到了,收工!
参考文章:标哥的技术博客