Today, I came across another problem in flash: the displaying of <img>'s in htmlText.
A whole lot of things turned out to be wrong:
- text is always wrapped around an image, even if there is no space at all, and even when <p>-tags or <br>-tags are used after the image;
- the image's height is not used when calculating the total height of a text component, if it is at the end of the text.
So I wrote a function that takes an html string, and changes it in such a way, so that images are displayed as they should have been displayed anyway.
You can check out the working example here, and the source code for the example is here.
Technical details:
- Flash adds 8px vspace and hspace to every image, unless it is explicitly set in the <img> tag;
- Flash adds 1/6th of extra space to a line where an image is set inside a font tag (<font size="30"><img ...><br></font>); Am I missing something, or is this just plain strange?!
So here's the function:
public function correctHtmlImageTextFlow(htmlTxt:String):String
{
/** put every &lt;img&gt; tag inside a &lt;font&gt; tag with the same fontHeight as the image,
* so text won't flow around it.
* But, since some mysterious margin of 1/6th is used when putting a &lt;br&gt; inside &lt;font&gt;,
* we'll have to calculate the fontHeight as imgHeight*5/6
*/
var currImgHeight:Number;
while (htmlTxt.match(/&lt;img[^&gt;]*height=.[0-9]+.[^&gt;]*&gt;/i))
{
currImgHeight = parseInt(htmlTxt.replace(/^.*?&lt;img[^&gt;]*height=.([0-9]+).[^&gt;]*&gt;.*$/i, "$1"));
// here, we temporarily rename &lt;img tags to &lt;xXxXimg tags, sow e won't match the tag again
htmlTxt = htmlTxt.replace(/(&lt;br&gt;)? ?&lt;(img[^&gt;]*height=.[0-9]+.[^&gt;]*&gt;) ?(&lt;br&gt;)?/i, '&lt;br&gt;&lt;font size="'+Math.ceil(currImgHeight*5/6)+'"&gt;&lt;xXxX$2&lt;br&gt;&lt;/font&gt;');
}
// now un-rename the &lt;xXxXimg tags
htmlTxt = htmlTxt.replace(/&lt;xXxXimg/gi, "&lt;img");
// remove optionally existing vspace and hspace from img tags (who uses this anyway??)
htmlTxt = htmlTxt.replace(new RegExp("(&lt;img[^&gt;]*)hspace=.[0-9]+.", "gi"), '$1');
htmlTxt = htmlTxt.replace(new RegExp("(&lt;img[^&gt;]*)vspace=.[0-9]+.", "gi"), '$1');
// now set vspace=0 and hspace=0 in the img tags
htmlTxt = htmlTxt.replace(new RegExp("&lt;img", "gi"), '&lt;img vspace="0" hspace="0"');
// done!
return htmlTxt;
}
If it helps you, then please leave a comment!
Note: I expected you to already clean the html: <br /> must already be converted to <br>, etcetera.
#1 by John - January 25, 2010 at 10:53 AM