Friday, March 4, 2011

How to Center Image when Rotating UIWebView

What happens, when you rotate iPhone while your application shows embedded webpage with custom background graphics? Hopefully the application rotates, too, and hopefully the background image has been designed well (*).

Here is an example how to top center backgroung image while rotating. Please note that the image has been poorly designed ON PURPOSE. Can't make a point with well designed graphics :)

Sample HTML file:
<html>
<head>
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>

<style TYPE="text/css">
body {
background-image:url('bg.png');
background-repeat:no-repeat;
background-position:center top;
background-attachment:fixed;
padding:10px;
padding-top:30px;
-webkit-text-size-adjust:none;
}
* {
-webkit-user-select: none;
}
</style>
</head>

<body>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</body>
</html>
Important parts of UIViewController containing UIWebView:
- (void)viewDidLoad {
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"bg" ofType:@"html"] isDirectory:NO];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    [super viewDidLoad];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}
* So what is "well designed graphics"? For example it does
  • Fade to background color at edges
  • Can be stretched to any size
  • Look nice when tiled

No comments:

Post a Comment