简体   繁体   中英

cocoa: How to make background transparent webView?

The mac osx ,I want to make my webview to look transparent and show the data on it with background showing images of parent view.

Can anyone please let me know how to do this? This method can not

NSString * source = @"<html><head><title></title></head><body><div id=\"box\">Example Box</div></body></html>";
[[webView mainFrame] loadHTMLString:source baseURL:[NSURL URLWithString:@""] ];
[[webView windowScriptObject] evaluateWebScript:@"document.getElementById('box').style.backgroundColor = '#dddddd';"]; // Change box background
[[webView windowScriptObject] evaluateWebScript:@"document.body.style.backgroundColor = '#dddddd';"]; // Change body background

You need to call setDrawsBackground: on the WebView and pass in NO . That will prevent the web view from drawing a background unless the page loaded in the web view explicitly sets the background color.

We can add background image in WebView using cocoa. to do this we need to add css for body tag.

Create a webview:

WebView *webView;

Fetch image form bundle path:

NSString *path = [[NSBundle mainBundle] pathForResource:@"my-bg" ofType:@"jpg"];

write Css for body tag.

NSMutableString *htmlBuilder = [[NSMutableString alloc] init];
[htmlBuilder appendString:@"body {"];
[htmlBuilder appendString:[NSString stringWithFormat:@" background-image: url('file://%@');",path]];
[htmlBuilder appendString:@"}"];

Load this image on webview

[[webView mainFrame] loadHTMLString:htmlBuilder baseURL:nil];
[webView setDrawsBackground:NO];

Your image will be added in background on webview.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM