Essential ActionScript 3.0 PHẦN 9 pot

94 367 0
Essential ActionScript 3.0 PHẦN 9 pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Formatting Text Fields | 721 COLOR Specifies the font color, as a 24-bit inte- ger hexadecimal num- ber preceded by the pound sign (#). For example, red is #FF0000 color KERNING Specifies whether to kern character pairs (1 means kern, 0 means don’t kern) kerning LETTERSPACING Specifies the distance between letters (i.e., the tracking), in pixels lettterSpacing <I> Specifiesitaliccharacter display None italic <IMAGE> Specifies a display asset to embed in the text field SRC The location of the asset (image, .swf file, or movie clip symbol) to embed in the text field None WIDTH The optional width of the embedded asset None HEIGHT The optional height of the embedded asset None ALIGN The optional horizon- tal alignment of the embedded asset None HSPACE The optional horizon- tal space surrounding the embedded asset None VSPACE The optional vertical space surrounding the embedded asset None ID Specifies an optional identifier bywhich the embedded asset can be referenced via the TextField class’s instance method getImageReference( ) None Table 27-5. ActionScript’s supported HTML tags (continued) Tag Description Attributes Description Equivalent TextFormat instance variable 722 | Chapter 27: Text Display and Input CHECKPOLICYFILE Specifies whether a policy file should be checked before the asset is accessed as data (see Chapter 19) None <LI> Specifies a paragraph displayed with a pre- ceding bullet; note that the bullet cannot be modified, and that no <UL> or <OL> is required None bullet <P> Specifies a paragraph ALIGN Specifies horizontal paragraph alignment (left, right, center, or justify) align CLASS Specifies the CSS class, for use with style sheets None <SPAN> Marks an arbitrary span of text so it can be for- matted with a style sheet CLASS Specifies the CSS class, for use with style sheets None <TEXTFORMAT> Specifies formatting information for a span of text LEFTMARGIN Specifies the horizon- tal distance, in pixels, between the left bor- der of the text field and the left edge of a paragraph leftMargin RIGHTMARGIN Specifies the horizon- tal distance, in pixels, between the right bor- der of the text field and theright edgeof a paragraph rightMargin BLOCKINDENT Specifies the distance, in pixels, a paragraph is indented from the text field’s left border blockIndent INDENT Specifies the distance, inpixels,aparagraph’s first line is indented from the text field’s left border indent Table 27-5. ActionScript’s supported HTML tags (continued) Tag Description Attributes Description Equivalent TextFormat instance variable Formatting Text Fields | 723 Generally speaking, the usage of the HTML tags in ActionScript listed in Table 27-5 matches that found in common web browsers. That said, there are some significant differences between the use of HTML in ActionScript and the use of HTML in web browsers, as follows: • The <TABLE> tag is not supported; use tab stops to simulate HTML tables. • In ActionScript, HTML is used primarily for formatting, and HTML content is not organized using the web-browser document metaphor. Therefore, the <HTML> and <BODY> tags are not required (but the <BODY> tag can optionally be used when formatting HTML with style sheets). • Unsupported tags are ignored, although their text content is preserved. • Flash requires quotes around the values assigned to tag attributes. See the sec- tion “Quoting attribute values.” • Hypertext links are not underlined automatically in Flash and must be under- lined manually using the <U> tag or the CSS text-decoration variable. • The <LI> tag does not support multilevel bullets or the <OL> (numbered list) tag. • Unterminated <P> tags do not cause line breaks in Flash Player as they do in reg- ular HTML. Closing </P> tags are required by Flash Player in order for line breaks to be added. • In Flash Player, <P> causes a single line break, exactly like <BR>, whereas in web browsers, <P> traditionally causes a double line break. • The <P> and <BR> tags do not cause a line break in text fields whose multiline variable is set to false. Furthermore, multiline is set to false by default. Hence, set multiline to true when using <P> and <BR>. • Hypertext links can be used to execute ActionScript code. For details, see the section “Hypertext Links,” later in this chapter. • The NAME attribute of the <A> tag is not supported by Flash Player, so internal links within a body of text are not possible. • In Flash, anchor tags are not added to the tab order and are therefore not acces- sible via the keyboard. LEADING Specifies the amount of vertical space, in pixels, between lines of text leading TABSTOPS Specifies horizontal tab stops, in pixels tabStops <U> Specifies underlined character display None underline Table 27-5. ActionScript’s supported HTML tags (continued) Tag Description Attributes Description Equivalent TextFormat instance variable 724 | Chapter 27: Text Display and Input Entity support ActionScript’s supported special character entities are listed in Table 27-6. Wherever an entity appears in a text field’s htmlText variable, Flash Player displays the corre- sponding character on screen. Numeric entities such as &#8482; (trademark sym- bol) are also supported. Quoting attribute values Outside Flash Player, HTML attribute values may be quoted with single quotes, dou- ble quotes, or not at all. The following tags are all valid in most web browsers: <P ALIGN=RIGHT> <P ALIGN='RIGHT'> <P ALIGN="RIGHT"> But in Flash Player, unquoted attribute values are not allowed. For example, the syn- tax <P ALIGN=RIGHT> is illegal in ActionScript. However, both single and double quotes may be used to delimit attribute values. When composing text field values that include HTML attributes, use one type of quote to demarcate the string itself and another to demarcate attribute values. For example, these examples are both valid: t.htmlText = "<P ALIGN='RIGHT'>hi there</P>"; t.htmlText = '<P ALIGN="RIGHT">hi there</P>'; However, this example would cause an error because double quotation marks are used to demarcate both the string and the attribute: // ILLEGAL! Do not use! t.htmlText = "<P ALIGN="RIGHT">hi there</P>"; Interactions between the text and htmlText variables Because the TextField variables text and htmlText can both assign the textual con- tent of a text field, care must be taken when using those variables in combination. When HTML tags are assigned to htmlText, the value of text will be that of htmlText, but with all HTML tags stripped out. For example, here we assign some HTML to a text field’s htmlText variable: Table 27-6. Supported entities Entity Character represented &lt; < &gt; > &amp; & &quot; “ &apos; ‘ &nbsp; nonbreaking space Formatting Text Fields | 725 var t:TextField = new TextField( ); t.htmlText = '<P ALIGN="LEFT">' + + '<FONT FACE="Times New Roman" SIZE="12" COLOR="#000000" ' + 'LETTERSPACING="0" KERNING="0">This field contains <B>HTML!</B>' + '</FONT></P>'; After the assignment, htmlText has the value: <P ALIGN="LEFT"><FONT FACE="Times New Roman" SIZE="12" COLOR="#000000" LETTERSPACING="0" KERNING="0">This field contains <B>HTML!</B></FONT></P> But text has the value: This field contains HTML! Take heed that successive assignments to htmlText and text overwrite each other. That is, assigning a new value to text overwrites the value of htmlText and vice versa. By contrast, successive concatenations (not reassignments) do not overwrite each other. For example, the following code assigns some HTML content to htmlText, then concatenates a string to that content via the text variable: var t:TextField = new TextField( ); t.htmlText = "<B>hello</B>"; t.text += " world"; After the concatenation, the value of htmlText is: <P ALIGN="LEFT"><FONT FACE="Times New Roman" SIZE="12" COLOR="#000000" LETTERSPACING="0" KERNING="0">hello world</FONT></P> As the preceding code shows, concatenating text to htmlText resets the text field’s formatting. When we assigned the value “world” to text, Flash removed the <B> tag we originally assigned to htmlText! Hence, mixing text and htmlText assignments is generally not recommended. HTML tags assigned directly to the TextField class’s instance variable text are never interpreted as HTML; they are always displayed verbatim. For example, the follow- ing code assigns a string including HTML tags to text and then concatenates a plain string to that content via the htmlText variable: var t:TextField = new TextField( ); t.text = "<B>world</B>"; t.htmlText += "hello"; After the concatenation, the value of htmlText is as follows: <P ALIGN="LEFT"><FONT FACE="Times New Roman" SIZE="12" COLOR="#000000" LETTERSPACING="0" KERNING="0">&lt;B&gt;world&lt;/B&gt;hello</FONT></P> Notice that the < and > characters in the <B> tag were converted to the HTML enti- ties &lt; and &gt;. 726 | Chapter 27: Text Display and Input Unrecognized tags and attributes Like web browsers, Flash Player ignore tags and attributes it does not recognize. For example, if we were to assign the following value to htmlText: <P>Please fill in and print this form</P> <FORM><INPUT TYPE="TEXT"></FORM> <P>Thank you!</P> The output would be: Please fill in and print this form Thank you! The <FORM> and <INPUT> elements are not supported by Flash Player so both are ignored (in fact, the unknown tags are stripped from htmlText!) Similarly, if we use container elements such as <TD>, the content is preserved but the markup is ignored. For example, in the following code: theTextField.htmlText = "<TABLE><TR><TD>table cell text</TD></TR></TABLE>"; outputs the following line without table formatting: table cell text However, if a tag is not terminated, the entire text that follows is considered part of the tag and will not display on screen. For example, given the following assignment: theTextField.htmlText = "We all know that 5 < 20. That's obvious."; Flash Player displays: We all know that 5 To include a < character in an HTML text field, use the entity &lt; as follows: theTextField.htmlText = "We all know that 5 &lt; 20. That's obvious."; Flash Player displays: We all know that 5 < 20. That’s obvious. For more information on including HTML source code in an HTML text field, see http://moock.org/asdg/technotes/sourceInHtmlField/ We’ve now seen how to format a text field using the TextFormat class and HTML. Now let’s look at the last tool for formatting text, the StyleSheet class. Formatting Text with the StyleSheet Class ActionScript’s StyleSheet class is used to format text fields using style sheets. Its func- tionality is based on a very limited subset of the W3C’s Cascading style sheets, Level 1 Recommendation (CSS1). Formatting Text Fields | 727 This section assumes a prior understanding of basic CSS concepts. If you are new to CSS, you should read the following introductions to CSS before continuing: • http://www.w3.org/TR/CSS21/intro.html • http://www.w3.org/MarkUp/Guide/Style But bear in mind that ActionScript does not support the full range of features in the W3C recommendation. As described in the W3C’s CSS recommendation, a stylesheet is a collection of rules that specify the presentation of a document. Each rule describes the style for a partic- ular element in an HTML or XML document. The following code shows an example rule that specifies the font color red for <H1> elements: h1 { color: #FF0000 } Within that rule, the selector (h1) indicates the element to which the style should be applied. The declaration block ( { color: #FF0000 }) contains one or more declara- tions describing the style that should be applied to the selected element. Each decla- ration ( color: #FF0000) contains a style property (color) and a value (#FF0000). Selectors are not case-sensitive, but style property names are. Here’s a simple style sheet that contains two rules, one for <p> elements and one for <li> elements: p { font-family: sans-serif font-size: 12px; } li { font-family: serif font-size: 10px; margin-left: 10px; } In ActionScript 3.0, a style sheet such as that shown in the preceding code is repre- sented by an instance of the StyleSheet class. Using the methods of the StyleSheet class, we can create a new style sheet programmatically or parse an existing external style sheet. To associate a StyleSheet object with a particular TextField object, we assign it to that TextField object’s styleSheet variable (covered later). Each text field can be associated with a single StyleSheet object only, in stark contrast to CSS1, where multiple style sheets can be associated with a single HTML or XML document. 728 | Chapter 27: Text Display and Input The specific properties available for use in an ActionScript style sheet are listed in Table 27-7. ActionScript supports only those W3C style properties that map to the formatting options of the TextFormat class. Compared to the full range of properties defined by the W3C, ActionScript’s set of supported properties is extremely limited. Style sheets can be used to add formatting to both XML elements and HTML ele- ments. However, among the HTML elements that Flash Player uses for formatting (see Table 27-5), only <P>, <LI>, and <A> tags can be formatted with style sheets. Other built-in tags (e.g., <B> and <I>) always perform their intended HTML-format- ting duty, and cannot be formatted with style sheets. Furthermore, <P> and <LI> always display as block elements, even when instructed to display as inline elements by a style sheet. To add formatting to the various interactive states of a hypertext link, use the follow- ing pseudo class selectors: a:link, a:hover, and a:active. For example, the following Table 27-7. Supported CSS style properties Style property name Description color Specifies the font color, as a 24-bit integer hexadecimal number preceded by the pound sign (#). For example, red is #FF0000. display Specifies whether the element should be hidden (none), followed by an automatic line break ( block) or not followed by an automatic line break (inline). font-family Specifies the device or embedded font name. font-size Specifies the font size, in pixels. font-style Specifies italicized character display (italic) or normal character display (normal, default). font-weight Specifies bold character display (bold) or normal character display (normal, default). kerning Specifies whether character pairs should be automatically kerned (true) or not (false, default). This property is an unofficial extension to the W3C set of supported style properties. leading Specifies the amount, in pixels, of vertical spacebetween lines oftext. This propertyis an unof- ficial extension to the W3C set of supported style properties. Compare with the W3C property line-height. letter-spacing Specifies the distance, in pixels, between letters (i.e., the tracking). margin-left Specifies thehorizontal distance,in pixels,between the left border of the textfield andthe left edge of a paragraph. margin-right Specifies the horizontal distance, in pixels, between the right border of the text field and the right edge of a paragraph. text-align Specifies horizontal paragraph alignment (left—the default—right, center, or justify). text-decoration Specifies graphical embellishments added to the text. Supported values in ActionScript are underline and none (the default). text-indent Specifies the distance, in pixels, a paragraph’s first line is indented from the text field’s left border (exactly like the TextFormat class’s instance variable indent). Formatting Text Fields | 729 rule specifies that hypertext links should be underlined when under the mouse pointer: a:hover { text-decoration: underline; } Style sheets give developers the critically important ability to separate style informa- tion from content, and to apply a single style definition to multiple bodies of con- tent. However, in ActionScript, style sheets have many limitations that diminish their potential usefulness. Before we learn how to format text using style sheets, let’s peruse those limitations. Notable style sheet limitations in ActionScript By design, Flash Player provides a minimal style sheet implementation only, intended as a style sheet–inspired interface for setting text field formatting options. As a result, Flash Player’s style sheet support lacks several important features found in the W3C’s CSS recommendation. Readers accustomed to working with CSS and HTML should stay mindful of the following Flash Player limitations: • All lengths are expressed in pixels. The relative unit em is not supported, and points are treated as pixels. • Each text field can be associated with one style sheet at a time only. Flash Player style sheets do not “cascade.” • Reassigning a text field’s style sheet does not cause the text field to be rendered in the newly assigned style sheet (for a workaround, see the example following this list). • The margin-top and margin-bottom properties are not supported. • Elements cannot be arbitrarily displayed as list items. The display property value list-item is not supported. Furthermore, list-item markers (i.e., bullets) cannot be customized, even for the built-in <LI> HTML element. • Flash Player supports basic type selectors and class selectors only. All other varieties of selectors are not supported. Furthermore, type selectors and class selectors cannot be combined (e.g., the following selector is illegal in Flash Player: p.someCustomClass). If a style sheet contains a descendant selector, the entire style sheet is ignored and no formatting is applied. • When a style sheet is assigned to a text field, that text field’s text content cannot be modified via replaceText( ), appendText( ), replaceSelText( ) or user input. To change a text field’s style sheet, first assign the desired StyleSheet object to styleSheet, then assign htmlText to itself, as follows: t.styleSheet = someNewStyleSheet; t.htmlText = t.htmlText; 730 | Chapter 27: Text Display and Input Note, however, that the new style sheet must set all style properties set by the old style sheet; otherwise, any unset old style property values will be retained. Now that we’re familiar with the general features and limitations of Flash Player’s style sheets, let’s see them in action. The following two sections describe how to apply a style sheet to a text field, first using a programmatically created style sheet, then using a style sheet loaded from an external .css file. Formatting text with a programmatically created style sheet To format text with a programmatically created style sheet, follow these general steps: 1. Create one or more generic objects representing rule declaration blocks. 2. Create a StyleSheet object. 3. Use the StyleSheet class’s instance method setStyle( ) to create one or more rules based on the declaration blocks created in Step 1. 4. Use the TextField class’s instance variable styleSheet to register the StyleSheet object with the desired TextField object. 5. Assign the desired HTML or XML content to the TextField object’s htmlText variable. Always register the StyleSheet object (Step 4) before assigning the HTML or XML content (Step 5). Otherwise, the style sheet will not be applied to the content. Let’s apply the preceding steps to an example. Our goal is to format all the text in a text field using the font Arial, size 20 pt, in bold (as we did earlier with the TextFormat class and with HTML). Once again, the text we’ll be formatting is the following simple HTML fragment: <p>ActionScript is fun!</p> In our style sheet, we’ll define a rule that tells Flash Player to display the content of all <P> tags in Arial, size 20 pt, bold. The declaration block for our rule is a simple generic object with dynamic instance variable names matching CSS-style properties and variable values specifying corresponding CSS-style values. Here’s the code: // Create the object that will serve as the declaration block var pDeclarationBlock:Object = new Object( ); // Assign style properties pDeclarationBlock.fontFamily = "Arial" pDeclarationBlock.fontSize = "20"; pDeclarationBlock.fontWeight = "bold"; In the preceding code, notice that when style sheets are created programmatically, the format for CSS property names changes slightly: hyphens are removed and [...]... variation (regular, bold, italic, or bold-italic) as one of the following four ActionScript constants: FontStyle.REGULAR, FontStyle.BOLD, FontStyle.ITALIC, FontStyle.BOLD_ITALIC Determining Font Availability | 7 49 fontType Indicates whether the font is an embedded font or a device font This variable refers to one of the following two ActionScript constants: FontType.EMBEDDED, or FontType.DEVICE Example 27-16... a fallback font automatically, as shown in Example 27- 19 Example 27- 19 Automatically selecting a fallback font package { import flash.display.*; import flash.text.*; public class FontFallbackDemo extends Sprite { public function FontFallbackDemo ( ) { var format:TextFormat = new TextFormat( ); 750 | Chapter 27: Text Display and Input Example 27- 19 Automatically selecting a fallback font (continued)... is highly subjective ActionScript offers a variety of advanced tools for fine-tuning the specific behavior of the FlashType renderer While a complete discussion of the FlashType renderer’s optional settings is beyond the scope of this book, for the sake of familiarity, Table 27 -9 lists the available tools and their basic purpose For further study, see each item’s entry in Adobe’s ActionScript Language... the Library, select the Verdana font symbol 7 From the pop-up Options menu, select Linkage Fonts and Text Rendering | 737 8 In the Linkage Properties dialog box, under Linkage, select Export For ActionScript 9 The Class box should automatically be set to Verdana If not, enter Verdana in the Class box This class name is used when loading fonts at runtime, as discussed in the later section “Loading Fonts... Flex Builder 2 and mxmlc To embed font outlines in a Flex Builder 2 ActionScript project or with the standalone compiler, mxmlc, we use the [Embed] metadata tag To use [Embed], we must give the compiler access to the Flex compiler-support library, flex.swc By default, all Flex Builder 2 projects automatically include flex.swc in the ActionScript library path, so in Flex Builder 2, the techniques covered... (italic), or bi (bold italic), matching the selected variation in the Font Symbol Properties dialog box The preceding pattern applies to Flash CS3 and Flash Player 9 but may change in the future That said, for backwards compatibility, hypothetical future versions of Flash Player will continue to support the preceding pattern Table 27-8 presents several examples of the preceding fontName pattern required... follows: styleSheet.setStyle(".specialnote", specialnoteDeclarationBlock); As in CSS, an ActionScript class selector is made up of a period followed by the desired class attribute value (in our case, specialnote) Example 27-8 revises our earlier style sheet example to demonstrate the use of CSS class selectors in ActionScript Example 27-8 Formatting applied to a specific class of paragraph var specialnoteDeclarationBlock:Object... our tag should behave like a paragraph, we set the display variable to block in the rule Example 27 -9 shows the complete code for styling a custom XML tag, with noteworthy differences from our preceding class-selector code shown in bold Example 27 -9 Formatting XML content with a style sheet var specialnoteDeclarationBlock:Object specialnoteDeclarationBlock.fontFamily specialnoteDeclarationBlock.fontSize... styleSheet.parseCSS(e.target.data); var t:TextField = new TextField( ); t.width = 200; t.styleSheet = styleSheet; t.htmlText = "ActionScript is fun!"; addChild(t); } } } The result of the code in Example 27-10 is identical to the result shown earlier in Figures 27-10 and 27-11 We’ve now finished our study of ActionScript s text formatting techniques In the next section, we’ll study several issues relating to font rendering... Text Entry Each text field’s ability to receive user input is governed by the value of its type variable By default, for text fields created with ActionScript, the instance variable type is set to TextFieldType.DYNAMIC, meaning that text can be modified through ActionScript but not by the user To allow a text field to receive user input, we must set type to TextFieldType.INPUT, as shown in the following . FACE="Times New Roman" SIZE="12" COLOR=" #00 000 0" ' + 'LETTERSPACING=" ;0& quot; KERNING=" ;0& quot;>This field contains <B>HTML!</B>' . ALIGN="LEFT"><FONT FACE="Times New Roman" SIZE="12" COLOR=" #00 000 0" LETTERSPACING=" ;0& quot; KERNING=" ;0& quot;>This field contains <B>HTML!</B></FONT></P> But. ALIGN="LEFT"><FONT FACE="Times New Roman" SIZE="12" COLOR=" #00 000 0" LETTERSPACING=" ;0& quot; KERNING=" ;0& quot;>hello world</FONT></P> As the preceding code

Ngày đăng: 12/08/2014, 16:21

Mục lục

    Part II Display and Interactivity

    Text Display and Input

    Formatting Text with HTML

    Interactions between the text and htmlText variables

    Unrecognized tags and attributes

    Formatting Text with the StyleSheet Class

    Notable style sheet limitations in ActionScript

    Formatting text with a programmatically created style sheet

    Formatting XML tags with CSS

    Formatting text with an externally loaded style sheet

Tài liệu cùng người dùng

Tài liệu liên quan