0

バンドルリソースにある画像があり、webViewでソースファイル(src = "")として参照する必要がありますstringByEvaluatingJavaScriptFromString。ウェブサイトから外部画像を参照することはできますが、ローカル画像のURLの書き方がわかりません。

これはどのように行うことができますか?

4

1 に答える 1

0

これを行う方法を示す例...

私のviewDidLoad場合、以下に示すように、いくつかのサンプルHTMLをUIWebViewに追加しています:(これは簡単にloadRequest:リモートURLへの呼び出しである可能性があります)

NSString *html = @"<html><body><img id='theImage'></img></body></html>";
[self.webView loadHTMLString:html baseURL:nil];

ビューコントローラをUIWebViewのデリゲートとして設定し、HTMLの読み込みが完了するまで待つ必要があります。次に、スクリプトを実行して画像のURLを修正できます。

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // Get the path to the image in the bundle you wish to display, and create a URL from this path.
    NSString *imagePath = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MyImage.png"]];
    NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
    // Create a script to execute in the web view.
    NSString *script = [[NSString alloc] initWithFormat:@"document.getElementById('theImage').src = \"%@\";", imageURL];
    // Execute the script.
    [self.webView stringByEvaluatingJavaScriptFromString:script];
    // Tidy up.
    [imagePath release];
}
于 2012-03-22T15:25:14.023 に答える