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 <img> tag inside a <font> 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 <br> inside <font>,
* we'll have to calculate the fontHeight as imgHeight*5/6
*/
var currImgHeight:Number;
while (htmlTxt.match(/<img[^>]*height=.[0-9]+.[^>]*>/i))
{
currImgHeight = parseInt(htmlTxt.replace(/^.*?<img[^>]*height=.([0-9]+).[^>]*>.*$/i, "$1"));
// here, we temporarily rename <img tags to <xXxXimg tags, sow e won't match the tag again
htmlTxt = htmlTxt.replace(/(<br>)? ?<(img[^>]*height=.[0-9]+.[^>]*>) ?(<br>)?/i, '<br><font size="'+Math.ceil(currImgHeight*5/6)+'"><xXxX$2<br></font>');
}
// now un-rename the <xXxXimg tags
htmlTxt = htmlTxt.replace(/<xXxXimg/gi, "<img");
// remove optionally existing vspace and hspace from img tags (who uses this anyway??)
htmlTxt = htmlTxt.replace(new RegExp("(<img[^>]*)hspace=.[0-9]+.", "gi"), '$1');
htmlTxt = htmlTxt.replace(new RegExp("(<img[^>]*)vspace=.[0-9]+.", "gi"), '$1');
// now set vspace=0 and hspace=0 in the img tags
htmlTxt = htmlTxt.replace(new RegExp("<img", "gi"), '<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