IOS UIwebView 加载网络图片 使用相对地址

方法一

  在html文件内直接使用file:///user//xx//image.png的绝对路径

  :这样可以显示图片,但是如果在程序目录修改,图片就不能显示

方法二

  在html使用占位符,如:在html内使用<image src="file:/[myimage]" height="200" width="320">

 在加载html文本的时候,replace这个占位符

 代码如下:

  string htmlpath=Path.GetFullPath("Docs/Detail.html");//根据html的相对路径获取html文件的绝对路径

  string htmltext=File.OpenText(htmlpath).ReadToEnd();//读取html的内容

  string  imagepath=Path.GetFullPath("Images/image.png").Replace("/","//").Replace(" ","%20");//读取图片的绝对路径后替换掉单斜杠和空格

  htmltext=htmltext.Replace("[myimage]",imagepath);//将html内容内的image占位符替换成正确的路径

  webview.LoadHtmlString(htmltext,null);//webview加载html内容

  :如果图片过多则处理很麻烦,只能做例子写写,不能真正使用

方法三

  使用webview.LoadHtmlString(htmltext,BaseUrl);//BaseUrl:sets the main page content and  base Url

  在方法三中,我们在html文件中图片地址只用使用相对地址了 <image src="Images/image.png" height="200" width="320">

  代码:

  NSUrl BaseUrl=new NSUrl(Path.GetFullPath("."),true);//获取程序的根目录路径

   webview.LoadHtmlString(htmltext,BaseUrl);//使用此重载方法的时候,图片的路径或自动处理成BaseUrl+image.src,这样图片就能正常显示了

 例如:

UIWebView *twoWebView =[[UIWebView alloc]initWithFrame:CGRectMake(0, 100, 200, 100)];

 jsString = [NSStringstringWithFormat:@"<html> \n"

                        "<head> \n"

                        "<style type=\"text/css\"> \n"

                        "body {font-size:%fpx; line-height:%fpx;background-color: transparent;}\n"

                        "</style> \n"

                        "</head> \n"

                        "<body>%@</body> \n"

                        "</html>"fontSize ,line_height,htmlText];

 NSURL *urlBai=[NSURLURLWithString:@"http://42.96.192.186"];

 [showWebView loadHTMLString:jsString baseURL:   urlBai];


[webView addSubview:twoWebView];

   :在使用次方法的时候,html更容易处理,程序也容易处理

综述:在以上三种方法种,第三种方法最优

转载于:https://www.cnblogs.com/someonelikeyou/p/3539537.html

猜你喜欢

转载自blog.csdn.net/weixin_34235371/article/details/94538687