iOS在UIWebView中加载图像

时间:2012-08-23 14:15:09

标签: ios image cocoa-touch uiwebview

拼命试图想出如何通过UIWebView将本地图像(保存在本地xcode包中)加载到以下HTML中。我花了无数个小时跟随其他指南,但似乎没有任何工作,所有扔错了。我试图在下面的NSString中添加一个本地图像,我写的是IMAGEGOESHERE -

{
    [super viewDidLoad];

    self.title = _restaurant.title;

    [[self navigationController] setNavigationBarHidden:NO animated:NO];

    self.activityIndicatorView.hidden = NO;
    [self.activityIndicatorView startAnimating];

    [self loadImageInNewThread];


    NSString *webViewContent = [NSString stringWithFormat:@"<html><head><style>* {font-family:   Helvetica}</style></head><body><center>%@ - %@<br><br><b>Restaurant:</b>%@</b><br>IMAGEGOESHERE<br></center></b></body></html>", _restaurant.openingTime,_restaurant.closingTime, _restaurant.name];

    [self.webView loadHTMLString:webViewContent baseURL:nil];
}

我希望你能帮忙,因为它让我疯了!

3 个答案:

答案 0 :(得分:2)

您需要先引用图像的路径:

 NSString *pathImg = [[NSBundle mainBundle] pathForResource:@"yourimage" ofType:@"png"];

然后在webViewContent中指定您的路径以及图片大小:

NSString* webViewContent = [NSString stringWithFormat:
                                   @"<html>"
                                   "<body>"
                                   "<img src=\"file://%@\" width=\"200\" height=\"500\"/>"
                                   "</body></html>", pathImg];

答案 1 :(得分:0)

此代码应该有效, 只需将yourFile替换为PDF的名称,将webView替换为webView的名称。 然后将Type替换为图像的扩展名。

//PDF View
       //Creating a path pointing to a file.pdf
       NSString *path = [[NSBundle mainBundle] pathForResource:@"yourFile" ofType:@"pdf"];
       //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];

答案 2 :(得分:0)

NSString *pathImg = [[NSBundle mainBundle] pathForResource:@"yourimage" ofType:@"png"];
NSString* webViewContent = [NSString stringWithFormat:
                               @"<html>"
                               "<body>"
                               "<img src=\"file://%@\" width=\"200\" height=\"500\"/>"
[webView loadHTMLString:webViewContent baseURL:nil];

您必须添加最后一行,其基本网址为nil