cocoa: How to make background transparent webView? - xcode

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.

Related

XCode Prevent UIWebView flashing white screen after Launch Image

I am fairly new to XCode - I'm designing an app with a single view that just displays a UIWebView that loads my jQuery mobile web site.
I have the Default.png and Default#2x.png files for the Launch images in place. When I run the app on my test device or in the emulator, it shows my Launch Image, and then flashes a white screen while the UIWebView loads the first page.
I know that I can change the background color and opacity so it will flash a different color than white, but I would like to prevent the flash altogether. I would like the app to launch, show the Launch image, and not show the UIWebView until the first page has completely loaded. Help?
# Andreas Volz (and anyone else wondering how I solved the problem of the white "flash")
First, add the name-of-loading-image.png and name-of-loading-image#2x.png files to your Xcode project. The regular image should be 320 x 460, and the #2x image should be 640 x 920.
Then, in my ViewController.h file I added these properties:
#property (nonatomic, retain) UIWebView *webView;
#property(nonatomic, strong) UIImageView *loadingImageView;
#end
And then in my ViewController.m file I added this:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController;
#synthesize webView;
#synthesize loadingImageView;
- (void)viewDidLoad
{
[super viewDidLoad];
//**************** Set website URL for UIWebView
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.example.com"] cachePolicy:NSURLCacheStorageAllowed timeoutInterval:20.0]];
//**************** Add Static loading image to prevent white "flash" ****************/
UIImage *loadingImage = [UIImage imageNamed:#"name-of-loading-image.png"];
loadingImageView = [[UIImageView alloc] initWithImage:loadingImage];
loadingImageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"name-of-loading-image.png"],
nil];
[self.view addSubview:loadingImageView];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
// Remove loading image from view
[loadingImageView removeFromSuperview];
}
To know when your webView has finished loading, you must implement the UIWebViewDelegate protocol.
In your viewController's .h file:
#interface viewController : UIViewController <UIWebViewDelegate>
{
UIWebView *webView;
}
#end
Then in your viewController's .m file, add this method:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"content loading finished");
// Display your webView
[self.view addSubview:webView];
}
You can use the -viewDidLoad method in your viewController's .m to continue displaying your launch image. You can also begin the loading of content for your webView:
- (void)viewDidLoad {
[super viewDidLoad];
// continue to display launch image
UIImage *launchImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"launchImage.png" ofType:nil ]];
UIImageView *launchImageView = [[[UIImageView alloc] initWithImage:launchImage] autorelease];
[self.view addSubview:launchImageView];
// now setup the base view for the webView controller
UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
contentView.backgroundColor = [UIColor blueColor];
// for rotation
contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.view = contentView;
//create a frame to size and place the web view
CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
UIWebView *aWebView = [[UIWebView alloc] initWithFrame:webFrame];
self.webView = aWebView;
//aWebView.scalesPageToFit = YES;
aWebView.autoresizesSubviews = YES;
aWebView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
//set the web view delegates for the web view to be itself
[aWebView setDelegate:self];
//determine the path the to the index.html file in the Resources directory
NSURL *url = [[NSBundle mainBundle] URLForResource:#"index" withExtension:#"html"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[aWebView loadRequest:requestObj];
}

Xcode iPhone SDK - Show gif image on app Launch

I currently have a mp4 video converted from a gif playing at app launch, but using a video stops playing music and has problems with airplay devices connected.
Anyways what i really want is showing my gif on app launch. But i can't seem to get the gif to "play" it only shows one frame, how do i make it play the whole gif ?
My current code:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Show Animation;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"Launch" ofType:#"mp4"]];
LaunchPlayer = [[MPMoviePlayerViewController alloc]
initWithContentURL:url];
LaunchPlayer.view.frame = self.view.bounds;
LaunchPlayer.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
LaunchPlayer.moviePlayer.controlStyle = MPMovieControlStyleNone;
LaunchPlayer.view.tag = 1;
[self.view addSubview:LaunchPlayer.view];
[LaunchPlayer.moviePlayer play];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(LaunchFinish)
name:#"MPMoviePlayerPlaybackDidFinishNotification"
object:nil];
}
Although I don't see how the code you posted has anything to do with using a .gif, you its sticking to the first frame because iOS will not run an animated .gif. However, you can export each frame of your animation as a separate image and animate them like this.
-(void) viewDidLoad
{
imageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"myImageFrame1.gif"],
[UIImage imageNamed:#"myImageFrame2.gif"],
[UIImage imageNamed:#"myImageFrame3.gif"],
[UIImage imageNamed:#"myImageFrame4.gif"], nil];
imageView.animationDuration = 2.0;
imageView.animationRepeatCount = 0;
[imageView startAnimating];
}
In my little example here. i used a UIWEBVIEW called webView and had spinning-loader.gif added as a resource. The image can me put anywhere in the project as long as its added. This showed the gif as well as made it animate. Hope this helps.
NSString *pathImg = [[NSBundle mainBundle] pathForResource:#"spinning-loader" ofType:#"gif"];
NSString* webViewContent = [NSString stringWithFormat:
#"<html><body><img style='width:85;height:85;' src=\"file://%#\" /></body></html>", pathImg];
[webView loadHTMLString:webViewContent baseURL:nil];
webView.scrollView.bounces = NO;
webView.scrollView.scrollEnabled = NO;
webView.opaque=FALSE;
[webView setBackgroundColor:[UIColor clearColor]];

loadHTMLString baseURL:nil not working in iOS5

I got a problem with UIWebView. I want to render my own html code in UIWebView.
if I use the below code, it's working fine.
NSBundle *thisBundle = [NSBundle mainBundle];
NSString *path = [thisBundle pathForResource:#"foo" ofType:#"html"];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[self.webView loadHTMLString:#"foo.html" baseURL:baseURL];
I want to render the html with below code. But it's not working. foo.html contains exactly the same content with the NSString* one. Any hints? Thanks in advance. =)
NSString* one = #"<html><head><title></title></head><body><img src=\"image.jpg\"/></body></html>";
[self.webView loadHTMLString:one baseURL:nil] ;
I use this code that works perfectly :
NSString* htmlContent = #"<html><head><title></title></head><body><img src='image.jpg' /></body></html>";
[self.webView loadHTMLString:htmlContent baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
Bu sure that image.jpg is included into your project.
create JS file demo.js and add code
var hello = function(str){
      return str;
};
add UIWebView => To embed JavaScript in a dummy html file and load that into the UIWebView
[self.webView loadHTMLString:#"<script src=\"demo.js\"></script>"
              baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];
Here is the code to make JS call
NString *str=#"hi JavaScript";
NSString *function = [[NSString alloc] initWithFormat: #"hello(%#)", str];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:function];
Now, there is one important safety tip to make this actually work: The UIWebView must actually be loaded a view. It doesn’t have to be visible, but in order for the WebKit engine to execute the JS, it must be on a view.

fill UIWebView with local "loading" image before internet content

I have a UITableView with header as a uiwebview (320*44px) for pub content. I wonder how to show some local content image or a background color or whatever before the content get loaded from the web ??
(goal: eleminate the white default background for not-loaded uiwebview banner)
//i assume ur webview object name as webView;
//i assume u were use delegate to ur webview by specifing after creating the webview like
webView.delegate=self;
//dont forget to in .h file #interface urViewController : vijayviewController<UIWebViewDelegate> { <UIWebViewDelegate> is matter.
UIImageView *imageView=[[UIImageView alloc]initWithFrame:webView.bounds];
[imageView setImage:[UIImage imageNamed:#"vijay.png"]];//image size should ur specification 320*44px
[imageView setTag:55];
[webView addSubview:imageView];
[imageView release];
//to remove image
// [[webView viewWithTag:55] removeFromSuperview];
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[[webView viewWithTag:55] removeFromSuperview];
}

How to resize WebView according to its content?

I want to set simple html contents within a web view and then resize it according to its content.
To set simple html contents within web view I used this code and it is working fine:
[[myWebView mainFrame] loadHTMLString:webViewContents baseURL:baseURLFramed];
Right now, if content is more than its actual size then it appears in web view showing both vertical and horizontal scroller in it. I want to set some default width and manage height according to its content in a way so that neither horizontal nor vertical scroller appears.
Can anyone suggest me some solution for it?
Thanks,
Miraaj
You can register as the WebView's frame load delegate, and when the page loads you can ask the main frame's document view for its size and resize the WebView. Make sure you turn off scrollbars on the frame or you will have problems.
Be aware that certain pages can be very large, when I tested daringfireball.net it came in at 17612 points high, which is obviously too large to display on-screen.
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
//set ourselves as the frame load delegate so we know when the window loads
[webView setFrameLoadDelegate:self];
//turn off scrollbars in the frame
[[[webView mainFrame] frameView] setAllowsScrolling:NO];
//load the page
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://daringfireball.net"]];
[[webView mainFrame] loadRequest:request];
}
//called when the frame finishes loading
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)webFrame
{
if([webFrame isEqual:[webView mainFrame]])
{
//get the rect for the rendered frame
NSRect webFrameRect = [[[webFrame frameView] documentView] frame];
//get the rect of the current webview
NSRect webViewRect = [webView frame];
//calculate the new frame
NSRect newWebViewRect = NSMakeRect(webViewRect.origin.x,
webViewRect.origin.y - (NSHeight(webFrameRect) - NSHeight(webViewRect)),
NSWidth(webViewRect),
NSHeight(webFrameRect));
//set the frame
[webView setFrame:newWebViewRect];
//NSLog(#"The dimensions of the page are: %#",NSStringFromRect(webFrameRect));
}
}
Another alternative is to ask the DOM for the height of your content.
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
NSString* heightOutput = [sender stringByEvaluatingJavaScriptFromString:#"document.getElementById(\"foo\").scrollHeight;"];
NSInteger height = [heightOutput integerValue];
[[self splitView] setPosition:height + 10 ofDividerAtIndex:0];
}
The key point here is to place your content inside of a named element so getElementById can be used. My implementation used a simple <div id="foo"> element.
In my particular case, my WebView was inside of a NSSplitView, so first resetting the height of the WebView to something small was causing a flicker.
I've got a sample project here demonstrating it.

Resources