Using TextFormat Objects

Using HTML tags in strings of text (as in Lesson 12, "Using XML with Flash") is not the only way to style text dynamically: TextFormat objects provide all the formatting power of HTMLand more!

As nothing more than special objects containing formatting properties for character and paragraph styles, TextFormat objects offer functionality similar to that of Cascading Style Sheets (CSS). After a TextFormat object has been defined, that object is then "applied" to a text field or section of text in a field, causing the affected text to take on the formatting style described by the object. A TextFormat object can be created and defined in one of two ways. Look at the following syntax:


var myStyle:TextFormat = new TextFormat(nameOfFont, size, color, bold, italic);


In this syntax, a TextFormat object is created and its formatting settings configured simultaneously. Here's an example:


var myStyle:TextFormat = new TextFormat("Arial", 12, 0x336699, true, true);


TIP

You can configure many additional formatting settings by using the constructor function.


The preceding syntax creates a TextFormat object named myStyle. This object represents a format that uses the Arial font at a point size of 12, using the color blue, and in bold italic. If you create the same TextFormat object using the alternative syntax, here's how it would look:


var myStyle:TextFormat = new TextFormat();

with(myStyle){

  font = "Arial";

  size = 12;

  color = 0x336699;

  bold = true;

  italic = true;

}


The preceding syntax uses a with statement to configure various formatting properties of the newly created object. Either way works, but the latter syntax is generally easier to read and use.

After you've created a TextFormat object, you can apply it to all or just a portion of the current text in the field, or to any new text entered into the field.

To apply a TextFormat object to all the text in a text field, use the following syntax:


myField_txt.setTextFormat(myStyle);


This script causes all text in the myField_txt text field to be displayed in the formatting style described by the myStyle TextFormat object. If the text had previously been styled using a different TextFormat object, that style is overwritten with the newly applied style.

To apply a TextFormat object to a single character in a text field, use the following syntax:


myField_txt.setTextFormat(27, myStyle);


This script causes the character at index position 27 to take on the style defined by the myStyle TextFormat object.

To style a range of characters in a field, use the following syntax:


myField_txt.setTextFormat(27, 50, myStyle);


This script causes the characters between index positions 27 and 50 to take on the formatting style described by the myStyle TextFormat object.

graphics/14inf09.gif

If you want the current text in the field to maintain its formatting while styling any new text entered into the field, use the setNewTextFormat() method. Look at the following syntax:


myField_txt.setNewTextFormat(myStyle);


Using this script, nothing in the myField_txt text field changes initially; however, any new text entered into it (either by the user or via ActionScript) takes on the character and paragraph formatting defined by the myStyle TextFormat object.

NOTE

This rule applies to new text entered at the end of any text currently in the field. If the insertion point is moved somewhere in the middle of the text, that text takes on the same formatting as the character just to the right of the insertion point.


At some point, you may need to know what formatting has been applied to a specific character or an entire text field (that is, which TextFormat objects have been applied), so that you can copy and apply that formatting elsewhere. You can get this information by using the getTextFormat() and getNewTextFormat() methods. To understand how these methods work, keep in mind that when you apply a TextFormat object to text in a field, Flash keeps a record of it, so to speak. For example, consider the following script, which assigns the myStyle TextFormat object to the myField_txt text field:


myField_txt.setTextFormat(myStyle);


Later, if you wanted another text field to be styled in the same way but weren't sure what style had been applied, you could use the following script to find out:


var newStyle:TextFormat = myField_txt.getTextFormat();


This script creates a new TextFormat object named newStyle that's automatically defined with the same formatting and character settings as the TextFormat object currently applied to myField_txt. The newStyle TextFormat object can then be applied to text fields. Just as the setTextFormat() method allows you to apply a format to a specific character or range of characters (as opposed to an entire field), the getTextFormat() method allows you to retrieve formatting data that has been applied at a specific character index or to a range of characters. Look at the following example:


var newStyle:TextFormat = myField_txt.getTextFormat(27);


This script creates a new TextFormat object named newStyle that's automatically defined with the same formatting and character settings as the TextFormat object currently applied to the character at index position 27. If you want to retrieve the formatting that's applied to new text entered into a field, as set with the setNewTextFormat() method, use the following syntax:


var otherStyle:TextFormat = myField.getNewTextFormat();


This script creates a TextFormat object named otherStyle that's automatically defined with the same formatting and character settings as the TextFormat object currently applied to new text entered into the myField_txt text field.

TextFormat objects have numerous properties that can be set to describe the formatting that the object represents. Many properties are self-explanatory, including align, bold, color, leftMargin, rightMargin, and so on. You may not be as familiar with the following properties:

  • font. This property represents the font face used by the object, using a string value such as "Arial" or "Times New Roman". Using the getFontList() method of the Text Field object in conjunction with this property, you can apply virtually any font face the user currently has installed on his or her machine. (We'll demonstrate the use of this property in the following exercise.)

  • tabStops. This property represents the distance (in points) that the caret moves within a field when the Tab key is pressed. This property's value is set by referencing the name of an array that contains positive numbers. For example, the following script creates an array with five numbers:

    
    var myTabStops:Array = [4, 20, 36, 52, 70];
    
    

    To use the values in this array to set the tabStops property of the style1 TextFormat object, you would use the following syntax:

    
    style1.tabStops = mytabStops;
    
    

    Any field using this TextFormat object will tab at 4, 20, 36, 52, and 70 points.

  • target. Used in conjunction with the url property, this property represents the window in which a URL opens when requested. This is similar to the target setting used with HTML.

  • url. This property represents a URL to which the text formatted as a TextFormat object is hyperlinked. This is a string value such as "http://www.macromedia.com".

In the following exercise, we'll access your computer's fonts to create TextFormat objects and apply them in various ways to the movingField_txt text field that we created earlier.

  1. Open flashWriter2.fla.

    We'll continue building on the file you used in the preceding exercise. In this exercise, you'll add script to Frame 1 of the Actions layer, script the buttons, and use the Checkbox component to facilitate part of the project's functionality.

  2. With the Property Inspector open, select the Checkbox component.

    The most important fact to know about this component is that its instance is applyToAll_cb. Knowing this, we can use the value property available to Checkbox components to determine whether the check box is currently checked (true) or not (false), and then act accordingly. For example, if the check box is currently checked, the following script places a value of true into the currentValue variable:

    
    var currentValue:Boolean = applyToAll_cb.value;
    
    

  3. With the Actions panel open, select Frame 1 of the Actions layer and add the following script at the end of the current script:

    
    var myFonts:Array = TextField.getFontList();
    
    

    This script creates an array named myFonts, which contains the names (as string values) of all fonts on the Flash Player host system (including fonts in the SWF file and any loaded asset SWF files). For example, after running the script on my machine, myFonts[3] has a value of "Arial". You can work with this array in the same manner as with any other array. The various values in this array randomly set font face styles for several TextFormat objects we'll create.

    NOTE

    When using the getFontList() method, you don't reference a particular text field instance name (as you might expect). Instead, you simply use TextField.

  4. Add the following lines of script at the end of the current script:

    
    var styleStatus:TextFormat = new TextFormat()
    
    with(styleStatus){
    
      font = myFonts[random(myFonts.length)];
    
      color = 0x858273;
    
      size = 16;
    
      bold = true;
    
    }
    
    

    The first line of this script creates a new TextFormat object named styleStatus. In a moment, you'll see how this object dictates the appearance of the text in the statusField_txt text field. The with statement defines several of the object's formatting parameters. Although most of the settings are fairly easy to understand, let's take a look at the line that sets the font property. The value of this property is set based on a random index value of the myFonts array. The expression uses the length of the myFonts array to generate a random number from all possible index values in the array. Thus, if the array has a length of 200, the number generated is between 0 and 199. That random number is then used to set the index value of one of the font names in the myFonts array. For example, if the number generated is 37, the expression would be evaluated as follows:

    
    font = myFonts[37];
    
    

    If the string value at that index is "DiscoMonkey", that's the name of the font face assigned to this TextFormat object.

    To apply the formatting of this new TextFormat object to the statusField_txt text field, we need to use the setTextFormat() method, which we'll do in the following step.

  5. Modify the updateStatus() function definition as shown:

    
    function updateStatus(){
    
      statusField_txt._x = movingField_txt._x;
    
      statusField_txt._y = (movingField_txt._y + movingField_txt._height) + 10;
    
      statusField_txt.text = movingField_txt.length;
    
      statusField._txt.setTextFormat(styleStatus);
    
    }
    
    

    graphics/14inf10.gif

    Note the last line of script that we added to this function definition: Remember that this function updates the position and text displayed in the statusField_txt text field. Here, we're using the setTextFormat() method to set the format of the statusField_txt text field to that described by the styleStatus TextFormat object. Because we've placed this line of script in the function definition, any changes to the format description of the styleStatus object will be reflected in statusField_txt when the function is called.

  6. Add the following script at the end of the current script on Frame 1:

    
    var style1:TextFormat = new TextFormat()
    
    with(style1){
    
      align = "left";
    
      bold = false;
    
      color = 0x1A1917;
    
      font = myFonts[random(myFonts.length)];
    
      indent = 0;
    
      italic = true;
    
      leading = 0;
    
      leftMargin = 20;
    
      rightMargin = 20;
    
      size = 20;
    
      target = null;
    
      underline = false;
    
      url = null;
    
    }
    
    

    This script creates another TextFormat object named style1. The with statement defines the formatting properties of that object. Note that the properties bold, indent, leading, target, underline, and url are set to false, 0, or null, in essence indicating that this TextFormat object should not use these properties.

    Although the TextFormat object could be defined even if we removed these lines of script, we've set them as shown for a reason. Assume you applied a TextFormat object (whose bold property was set to true) to a text field. The text in that field would appear in boldsimple enough. Now suppose you apply a different TextFormat object (whose bold property was not explicitly set) to that same field. In this case, the text in that field would still appear bold, although it would take on the other characteristics of the newly applied TextFormat object. For a formatting characteristic to change when applying a new TextFormat object, that new object must specifically define a different value; otherwise, the old value (and its effect) remains. This same principle applies when using the setNewTextFormat() method; therefore, it's good practice to always define something for property values so that you get the results you intended.

  7. Add the following script at the end of the current script on Frame 1:

    
    var style2:TextFormat = new TextFormat()
    
    with(style2){
    
      align = "center";
    
      bold = false;
    
      color = 0xCC0000;
    
      font = myFonts[random(myFonts.length)];
    
      indent = 0;
    
      italic = false;
    
      leading = 15;
    
      leftMargin = 0;
    
      rightMargin = 0;
    
      size = 14;
    
      target = null;
    
      underline = false;
    
      url = null;
    
    }
    
    

    This script creates another TextFormat object named style2.

    NOTE

    The accompanying source file for this exercise has defined two additional TextFormat objectsstyle3 and style4. To avoid redundancy (because these objects are similar to the ones already defined) as well as to save trees, we're not including the syntax for these two objects here.

    We've now defined all the TextFormat objects for the project. Before we put them to use, however, we need to tweak the script's flow in Frame 1 just a bit.

  8. Move the updateStatus() and reshapeBox() function calls from just above where it says movingField_txt.onChanged = function(){ to the end of the script on Frame 1.

    graphics/14inf11.gif

    As always, it's a good idea to put all initial function calls at the end of a script, but there's an especially good reason now. Remember that in Step 5 we modified the updateStatus() function to include a line of script that uses the styleStatus TextFormat object. If we had left that function call where it was, the updateStatus() function would have been called a split second before the script that creates and defines the styleStatus TextFormat object. This would have resulted in a minor bug because you can't use something before it's created. By moving the function calls to the end of the script, we've ensured that all objects are created and defined first.

    The last action we need to perform is scripting the buttons.

  9. Add the following event handler at the end of the current script:

    
    style1_btn.onRelease = function(){
    
      if (applyToAll_cb.value){
    
        movingField_txt.setTextFormat(style1);
    
        movingField_txt.setNewTextFormat(style1);
    
      }else{
    
        movingField_txt.setNewTextFormat(style1);
    
      }
    
      updateStatus();
    
      reshapeBox();
    
    }
    
    

    This step adds an onRelease event handler to the style1_btn instance. This handler takes one of two actions, depending on whether the Checkbox component (named applyToAll_cb) is checked or unchecked when the button is clicked. The if statement says that if its value is true (the checkbox is checked), we want to apply the style1 TextFormat object to all currently displayed text in the movingField_txt text field (setTextFormat()), as well as any new text entered into that field (setNewTextFormat()). This action causes all text in that field to immediately reflect the new formatting style. If the checkbox's value is false (else), the style1 TextFormat is applied only to new text entered. After either of these sets of actions has executed, the updateStatus() and reshapeBox() functions are called to handle any changes that need to be made to the statusField_txt text field and the box_mc movie clip instance as a result of the new formatting.

  10. Place three similar scripts below the current script, changing style1 to read style2, style3, and style4, respectively.

  11. Choose Control > Text Movie to test the project.

    When the movie appears, test the various buttons in conjunction with the check box to see the effect that it has on the text in the movingField_txt text field. All the functionality from the preceding exercise should be retained as well.

  12. Close the test movie and save your work as flashWriter3.fla.

    This completes the exercise. As you've learned, TextFormat objects provide a lot of power and flexibility for formatting text. But the formatting fun doesn't end there. No, as you'll learn later in this lesson, Flash provides a means to tap into one of the most popular means of formatting textCascading Style Sheets.