Alternative Method to Display HTML Text in Dynamic Textfields
Wednesday, December 9th, 2009
I have been trying to figure out the best way to display HTML text in dynamic text fields for ActionScript 3.0 projects over the past six months. The best solution for Five Star is one that keeps the file size small, is versatile enough to handle different fonts with ease and adapts to different projects with little or no customization.
The solution that has evolved is a function named DisplayText, which I have copied below. The comments explain how the function works and an example call is included.
If you try implementing this solution and find it useful, if you need help or would like to enhance it, please leave a comment below.
/**
* Takes a string of text that may have bold and italic tags.
* Displays string properly in an HTML TextField by replacing the bold and italic
* tags with font tags.
* Fonts should be linked in the library.
* Each version (regular, bold, italic) should have its own link.
* If 2 versions of the font (ex. regular and italic) have the same name
* in the Font Symbol Properties dialog Font menu you don't need specify the italic
* or bold version.
* Example Call:
* var s:String = "Hi, and welcome to <b>Lesson 1:</b><i>Topic 1</i>."
* DisplayText( display_txt, s, 13, "Franklin Gothic Book", "Franklin Gothic Demi" );
* @param tf TextField to format
* @param s Text to place.
* @param size Size of text display.
* @param defaultFont Regular font.
* @param boldFont Optional. Bold font.
* @param italicFont Optional. Italic font.
*/
function DisplayText ( tf:TextField,
s:String,
size:Number,
defaultFont:String,
boldFont:String = "",
italicFont:String = "") : void
{
tf.htmlText = true; // Set this to allow HTML text to be set
tf.embedFonts = true; // Set embed fonts to true
tf.text = s; // Assign text - but not as htmlText yet
// If a bold font is specified, replace bold tags
if ( boldFont != "")
{
var boldStart:RegExp = /<b>|<B>/gi; // Match opening bold tags
var boldEnd:RegExp = /<\/b>|<\/B>/gi; // Match ending bold tags
tf.text = tf.text.replace( boldStart , "<font face='" + boldFont + "'>" );
tf.text = tf.text.replace( boldEnd , "</font>" );
}
// If a italic font is specified, replace italic tags
if ( italicFont != "")
{
var italicStart:RegExp = /<i>|<i>/gi; // Match opening italic tags
var italicEnd:RegExp = /<\/i>|<\/I>/gi; // Match ending italic tags
tf.text = tf.text.replace( italicStart , "<font face='" + italicFont + "'>" );
tf.text = tf.text.replace( italicEnd , "</font>" );
}
// Wrap the text in a tag defining default font face and size
tf.text = "<FONT FACE='" + defaultFont + "' SIZE='" + size + "'>" +
tf.text + "</FONT>";
// Assign the text
tf.htmlText = tf.text;
}
