有時候我們需要用webView加載一些html網(wǎng)頁來展示某些業(yè)務內容兵睛,但是有時候網(wǎng)頁里的圖片總是不能按照屏幕尺寸進行顯示,往往由于網(wǎng)頁圖片過大導致瀏覽效果極差窥浪。因此要么給出適配好的內容文件祖很,要么只能前端去處理了。
由此記下處理辦法漾脂,以免以后遇到相同的問題及時去處理假颇。
準備一個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()"];
}
處理完的效果是這樣的:
好了姜钳,我們的效果達到了,收工形耗!
參考文章:標哥的技術博客