views:

442

answers:

2

I would like to diplay HTML in iPhone UIWebView. My HTML looks like

text
text
<img src.../>
text
text

How can I cause the component (via JavaScript or Objective C) to fit the image size to a window - i.e text size will remain the same but image will be reduced/enlarged proportionally to prevent horizontal scrolling ?

Thanks

A: 

You can use a percentage or ems to size the image in CSS. This means you need to convert the pixel sizes of the images to percentages or ems. You should also use jpeg as they scale better.

This article by Jon Tan is my favourite on the subject and pretty much explains the whole process.

matpol
+3  A: 

You have to know what the HTML looks like, because the only way to do that is to manipulate the DOM.

On the Mac you could access the DOM via Objective C, but that API isn't available on iPhone. Luckily you can do the same via the UIWebView javascript bridge.

Suppose the HTML looks like this:

text
text
<img id="myimage" src="..." height="150" width="150"/>
text
text

You add a JS function similar to this to the HTML:

<script>
function enlargeImage(w, h)
{
   var img = document.getElementById("myimage");
   img.width = w;
   img.height = h;
}
</script>

Then you simply call something like:

[webView stringByEvaluatingJavaScriptFromString:@"enlargeImage(300, 300)"];

The only caveat being that you should wait for the HTML is completely loaded via the webViewDidFinishLoad delegate callback.

Clearly you can also take shortcuts like:

[webView stringByEvaluatingJavaScriptFromString:
    @"document.getElementById("myimage").width = 300;"];
[webView stringByEvaluatingJavaScriptFromString:
    @"document.getElementById("myimage").height = 300;"];
duncanwilcox
You are hero!!!
sfa