2013-10-08 47 views
0

我在下面試過兩種方法,但只有白色背景出現,沒有圖像顯示。如何在UIWebView中加載圖像

1.

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"png"]; 
[myWebView loadHTMLString:[NSString stringWithFormat:@"<html><body><img src=\"file://%@\"></body></html>",path] baseURL:nil]; 

2.

NSString *path = [[NSBundle mainBundle] pathForResource:@"yourImage" ofType:@"png"]; 
//Creating a URL which points towards our path 
NSURL *url = [NSURL fileURLWithPath:path]; 
//Creating a page request which will load our URL (Which points to our path) 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
//Telling our webView to load our above request 
[webView loadRequest:request]; 

我認爲都是正確的方法,但都是無用的我。 Plz幫助我。

+0

ya thanku.But我完成了第二種方法,我在做一個愚蠢的錯誤。 –

回答

0
  1. 使用圖像數據(test_image.jpeg在束會在web視圖被加載)

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test_image" ofType:@"jpeg"]; 
    NSData *data = [NSData dataWithContentsOfFile:filePath]; 
    [webView loadData:data MIMEType:@"image/jpeg" textEncodingName:@"utf-8" baseURL:nil]; 
    
  2. 加載爲HTML內容

    NSURL *imageUrl = [[NSBundle mainBundle] URLForResource:@"test_image" withExtension:@"jpeg"]; 
    NSString *htmString = [NSString stringWithFormat:@"<!DOCTYPE html><html><body><img border=\"0\" src=\"%@\" width=\"304\" height=\"228\"></body></html>", [imageUrl absoluteString]]; 
    [webView loadHTMLString:htmString baseURL:nil]; 
    

正如我認爲最好的辦法是爲加載HTML內容。如果你想要,你可以按照你的意願設計html內容。

0

兩者都適合我。

您確定您已將您的xib中的webview與IBOutlet鏈接起來嗎?

@property (nonatomic, weak) IBOutlet UIWebView *webView; 

這樣對您的XIB(或故事板):

enter image description here