如何在UIWebView中加载图像

时间:2013-10-08 07:07:19

标签: ios6 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帮助我。

2 个答案:

答案 0 :(得分:0)

两者都很适合我。

您确定已将xib中的webview与IBOutlet链接?

@property (nonatomic, weak) IBOutlet UIWebView *webView;
在你的XIB(或故事板)上像这样:

enter image description here

答案 1 :(得分:0)

  1. 使用图像数据(捆绑中的test_image.jpeg将在webView中加载)

    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];
    
  3. 我认为最好的方法是加载HTML内容。如果您愿意,可以根据需要设置html内容的样式。

相关问题