UIWebView - scaling image independently from text

孤者浪人 提交于 2020-01-03 02:46:05

问题


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


回答1:


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;"];



回答2:


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.



来源:https://stackoverflow.com/questions/1790346/uiwebview-scaling-image-independently-from-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!