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("/","http://").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更容易處理,程序也容易處理
綜述:在以上三種方法種,第三種方法最優
posted on 2014-02-07 15:05 ACM_Someone like you 閱讀(1738) 評論(0) 收藏 舉報
浙公網安備 33010602011771號