as3 embedding fonts and using variations in textformats

Hello,

I’m posting this to help others who have searched for help on this topic and only found Flex examples with embed tags etc.

Platform: AS3 in flash IDE

Scenario: I want to

  • embed fonts
  • be able to change the textformat applied to a textfield in order to switch the font between Verdana normal to Verdana bold

Solution:

  1. Add two new fonts to the library, both Verdana, one with the ‘bold’ checkbox ticked and one without. The class and name fields you choose do not matter, but do export for actionscript on the first frame.
  2. Create a TextField on stage with the instancename ‘input’. Rotate it since only embedded fonts will show in rotated textfields.
  3. Create two Buttons on stage with instancenames ‘b1’ and ‘b2’
  4. add code to frame:


// Note that for a font with class linkage 'VerdanaNormal',
// new VerdanaNormal().fontName == "Verdana", and this is
// the value that TextFormat expects for the .font property.
// The crux here is that the same font was added
// to the library twice, once for each variation,
// and the class linkage and name are not used here.

var tf1:TextFormat = new TextFormat();
tf1.font = "Verdana";
tf1.bold = false;

var tf2:TextFormat = new TextFormat();
tf2.font = "Verdana";
tf2.bold = true;

input.embedFonts = true;
input.htmlText = "This is the text to test with."

b1.addEventListener(MouseEvent.CLICK, onB1Click);
b2.addEventListener(MouseEvent.CLICK, onB2Click);


function onB1Click(eo:MouseEvent) {
    trace("setting tf1, .bold=false");
    input.setTextFormat(tf1);
}
function onB2Click(eo:MouseEvent) {
    trace("setting tf2, .bold=true");
    input.setTextFormat(tf2);
}