Dynamic text characters colour in AS3
I was contacted with a question about how to change the colour of the first character in a dynamic text field without affecting the rest of the characters. For my solution I have used the charAt() and the substr() methods from the String class to store the first character and the other characters from the dynamic text in a string. Then I used the htmlText property from the Text class so I could use the font tag to change the colour of the first character.
//This is the text to be displayed in the dynamic text field.
var displayText:String = "Hello";
//This stores the first character from the displayText using the charAt() method.
//This method returns a character specified by the index parameter value. I have
//use the value 0 which is the first character in a string.
var firstCharacter:String = displayText.charAt(0);
//This stores the other characters in the displayText using the substr() method.
//This method returns characters based on the start position and the length of the
//a string. I have specified the start position to be ‘1’ which is the second character of
//the displayText, and displayText.length of the length of the string which be other
//characters in the displayText.
var otherCharacers:String = displayText.substr(1,displayText.length);
//This uses the font tag from the htmlText property to assign a different colour
//to the first character.
mytxt_txt.htmlText = '<font color="#DD0000">' + firstCharacter + '</font>'+ otherCharacers;
In the code above the dynamic text field has the instance name ‘mytxt_txt’. You will also need to check the render as html button for the htmlText to work.



0 comments:
Post a Comment