Lines 14 through 17 create four private properties that reference two loaders, the CSS data, and a text field used to display a definition when the user clicks on a term in a link.. In l
Trang 1Now we come again to a point where you should stretch the mental muscles
and try to take what you’ve learned one step further The first topic of this
sec-tion will give you a peak at what we’ll be covering in Chapter 13: loading
exter-nal assets You’ll learn how to load and apply exterexter-nal HTML and CSS files
The second topic of this section will give a brief overview of the new Text
Layout Framework that brings some advanced typographic support to
ActionScript We’ll list a few pros and cons of this new technology and then
show you a few examples of how to use TLF fields that differ from uses of
ordinary text fields
Loading HTML and CSS
This exercise uses the same HTML, CSS, and some of the ActionScript from
the prior HTML and CSS example but loads the content from external files
We’ll discuss loading again in Chapter 13, but here we’ll just focus on loading
text files
The assets you’ll need for this exercise are included with the source code from
the companion website, but here are the setup files in case you wish to
recre-ate them on your own The following files should go in the same directory
as your host .fla file In case you want to try the sample files, they’re found
in the LoadHTMLCSS_Example directory of the source archive, and the FLA
uses the class as a document class
HTML (demo.html)
<body>
<p class='heading'>ActionScript 10.0 Adds Time Travel</p>
<p class='byline'>by Walter Westinghouse</p>
<p>January 1, 2015 The rumors swirling around the tech
community recently have been confirmed today as lead
Flash Player engineer, Dr Eldon Tyrell, announced that
ActionScript 10.0 will support time travel Ever since
the concept of time travel was popularized by
<a href="event:author of early science fiction novel,
The Time Machine">H G Wells</a> in 1895, humans have
yearned for the ability to travel through time, and now
it's a reality.
</p>
<p>Flash Player QA lead Roy Batty, agreed "We're happy to
add this feature to human BioChips everywhere using the
standard Express Install Opt-In process Flash Player has
long been a leader in bringing immersive experiences to
humans Just search <a href="http://www.google.com"
target="_blank"> Google</a> for your favorite feature and
you'll likely find that it's supported."
</p>
<p>Users of the antiquated "desktop computing" model can't
take advantage of this feature, nor can users of the
recently standardized HTML5.
</p>
</body>
Pu sh You rself!
N OT E
When text resides in an external file and you’re not assigning strings to variables
in ActionScript, nested quotes are typi-cally not a problem and don’t have to be escaped with a backslash character.
Trang 2Loading HTML and CSS
CSS (demo.css)
body { font-family: Verdana;
text-indent: 20px;
} heading { font-size: 18px;
font-weight: bold;
text-indent: -20px;
letter-spacing: 1px;
color: #FF6633;
} byline { font-size: 14px;
font-style: italic;
text-align: right;
} a:link { color: #000099;
text-decoration: underline;
} a:hover { color: #990099;
} ActionScript (LoadHTMLCSS_Eample.as)
Loading HTML and CSS from external files requires use of the URLLoader and
URLRequest classes The loading process is the same for both HTML and CSS,
so we’ll focus on one and discuss the other briefly You’ll also use the Event COMPLETE event to continue after the loading is complete
Lines 1 through 12 set up the class by creating the package, importing required classes, and creating the class Lines 14 through 17 create four private properties that reference two loaders, the CSS data, and a text field used to display a definition when the user clicks on a term in a link
1 package {
2
3 import flash.display.MovieClip ;
4 import flash.events.Event ;
5 import flash.events.TextEvent ;
6 import flash.net.URLLoader ;
7 import flash.net.URLRequest ;
8 import flash.text.StyleSheet ;
9 import flash.text.TextField ;
10 import flash.text.TextFormat ;
11
12 public class LoadHTMLCSS_Example extends MovieClip {
13
14 private var _cssFile: URLLoader ;
15 private var _htmlFile: URLLoader ;
16 private var _css: StyleSheet ;
17 private var _definitionField: TextField ;
Trang 3The constructor sets up the CSS loading, so we’ll focus on that in detail Line
19 creates an instance of the URLLoader class that you can monitor Lines 20
through 22 add a listener to that instance, which calls the onLoadCSS()
func-tion when the load is complete Line 23 creates an instance of the URLRequest
class for the URL that points to our external CSS file A URLRequest object is
used for all loads and allows for consistent handling of URLs throughout
ActionScript 3.0 Line 24 loads the CSS
18 //constructor
19 public function LoadHTMLCSS_Example() {
20 _cssFile = new URLLoader ();
21 _cssFile addEventListener ( Event.COMPLETE , onLoadCSS,
22 false , 0, true );
23 var req: URLRequest = new URLRequest ( "demo.css" );
24 _cssFile load (req);
25 }
When the CSS document loads, the function in the following code block is
called Line 28 creates a new StyleSheet instance, and line 29 parses the CSS
data sent to the listener function Note the use of the data property to retrieve
this information from the event’s target (in this case, the cssFile instance
responsible for the loading) The style sheet is now ready to be applied, but
neither the HTML nor the text field exist yet
Next on the to-do list is the exact same procedure for the HTML file Line
30 creates the URLLoader instance, a listener is added to the instance in lines
31 and 32, a URLRequest instance is created in line 33, and the file is loaded
in line 34
26 //loading style sheet
27 private function onLoadCSS(evt: Event ): void {
28 _css = new StyleSheet ();
29 _css parseCSS (evt target data );
30 _htmlFile = new URLLoader ();
31 _htmlFile addEventListener ( Event.COMPLETE , onLoadHTML,
32 false , 0, true );
33 var req: URLRequest = new URLRequest ( "demo.html" );
34 _htmlFile load (req);
35 }
Once the HTML is fully loaded (triggering the listener function in the
fol-lowing code block), it’s put into the htmlString variable (line 38) In line 40, a
text field is created that will hold the body copy from the story in the loaded
HTML Lines 41 through 52 do nothing that we haven’t already covered, but
it warrants repeating that the CSS is applied before the HTML is added to
the field (lines 47 and 48, respectively) Also, a listener is added to trap any
link-based ActionScript triggered by an HTML anchor tag’s event: protocol
This event will be used to show a definition of a term clicked on in the main
body text
Lines 54 through 57 create a TextFormat instance to format any definition
displayed, and lines 59 through 66 create the field to hold that definition The
last thing the function does is clean up a bit by removing the listeners from
N OT E
Even though the req variable appears
in the constructor function, it can be reused without concern because declar-ing a variable inside a function makes the variable local to that function.
Trang 4Loading HTML and CSS
the two URLLoader instances, because everything has loaded successfully at that point in the code
The last functions in the class, onTextEvent() places the definition sent by any event: link click to the _definitionField text field
36 //loading html
37 private function onLoadHTML(evt: Event ): void {
38 var htmlString: String = evt target.data ;
39
40 var storyField: TextField = new TextField ();
41 storyField x = storyField y = 20;
42 storyField width = 500;
43 storyField height = 330;
44 storyField multiline = true ;
45 storyField wordWrap = true ;
46 storyField selectable = false ;
47 storyField styleSheet = _css;
48 storyField htmlText = htmlString;
49 storyField addEventListener ( TextEvent.LINK ,
50 onTextEvent,
51 false , 0, true );
52 addChild (storyField);
53
54 var definitionFormat: TextFormat = new TextFormat ();
55 definitionFormat font = "_sans" ;
56 definitionFormat size = 12;
57 definitionFormat italic = true ;
58
59 _definitionField = new TextField ();
60 _definitionField x = 20;
61 _definitionField y = 360;
62 _definitionField width = 500;
63 _definitionField height = 20;
64 _definitionField mouseEnabled = false ;
65 _definitionField defaultTextFormat = definitionFormat ;
66 addChild (_definitionField);
67
68 _cssFile removeEventListener ( Event.COMPLETE ,
69 onLoadCSS);
70 _htmlFile removeEventListener ( Event.COMPLETE ,
71 onLoadHTML);
72 }
73
74 private function onTextEvent(evt: TextEvent ): void {
75 _definitionField text = evt text ;
76 }
77 }
78 } With this exercise as a basis for future work, you can control the text format-ting for very large projects by applying a project-wide CSS document to every applicable text field This also makes your development process much easier because you can edit the external CSS file and its styles will be updated every-where the file is used The document in Figure 10-7 was created using external HTML data and formatted using a CSS document
Trang 5ActionScript 10.0 Adds Time Travel
by Walter Westinghouse
January 1, 2015 The rumors swirling around the tech community recently
have been confirmed today as lead Flash Player engineer, Dr Eldon Tyrell,
announced that ActionScript 10.0 will support time travel Ever since the
concept of time travel was popularized by H G Wells in 1895, humans have
yearning for the ability to travel through time, and now it's a reality.
Flash Player QA lead Roy Batty, agreed "We're happy to add this feature
to human BioChips everywhere using the standard Express Install Opt-In
process Flash Player has long been a leader in bringing immersive
experiences to humans Just search Google for your favorite feature and you'll
likely find that it's supported."
Users of the antiquated "desktop computing" model can't take advantage
of this feature, nor can users of the recently standardized HTML5.
Figure 10-7 Text loaded and styled from external HTML and CSS data
Text Layout Framework
Integrated in Flash Professional CS5 and Flash Builder 4, a new text
mecha-nism called Text Layout Framework (TLF) brings unprecedented control over
type to the Flash Platform TLF requires Flash Player 10 and the following are
just a few of things that TLF offers:
• Added character styles including subscript, superscript, underline,
strik-ethrough, case conversion, enhanced leading, ligatures, highlight color,
and more
• Added paragraph styles including multicolumn support with gutter
width, last line justification options, enhanced margins and indents,
para-graph spacing, padding, and more
• Text flow across multiple linked text containers
• Support for alpha and rotation transformations when using device fonts
• Support for 3D rotation, color effects, and blend modes without first
plac-ing the field into a movie clip or sprite
• Support for right-to-left text for languages like Arabic and Hebrew
• Support for bidirectional text, or right-to-left text that can contain
ele-ments within it that flow left-to-right This is important for embedding
English words or numbers within Arabic or Hebrew text, for example
Along with TLF’s extensive feature set comes complexity We want to stress
that we consider TLF to be an intermediate to advanced feature, depending
on how deeply you want to delve into its inner workings Documentation, in
particular, is still in its infancy However, we thought it important to discuss
Pu sh You rself!
Trang 6Text Layout Framework
TLF in this book because it offers several useful text features not supported
by the traditional Flash Platform text technology (now called Classic text, and covered throughout this chapter)
For basic use, the ActionScript syntax for creating and manipulating TLF fields is very similar to that of Classic text fields, so we’ll avoid straight repeti-tion wherever possible For the following exercises, we’ve chosen a practical subset of TLF’s features that are likely to be useful in a variety of situations and apply to the widest range of possible users We’re just discussing the tip
of the proverbial iceberg, however Please consider this section an introduc-tion to TLF—a trial run that will, at best, encourage you to explore addiintroduc-tional capabilities and, at minimum, provide you with a set of code blueprints that you can adapt for your own use
Rotating device fonts
Using Classic text fields, rotating a field will cause device fonts to disappear The workaround for this issue is to embed the font in your SWF—after which the text will display correctly The problem is, every font symbol you embed contributes to file size, and adding TLF fields to your files requires only a one-time file size increase for each user (which we’ll discuss at the end of this section) So, if you intend to use many device fonts, or even several variants
of a small number of device fonts, you may be better served by using TLF The following code, found in the tlf_rotation.fla source file demonstrates
rotation of both Classic and TLF text fields The Classic field is positioned
at x, y coordinates (20, 20), and the TLF field is placed at (100, 100) In the former case, the rotation causes the device font text to disappear However, the same device font used in the TLF field remains visible
1 import fl.text.TLFTextField ;
2
3 var txtFld: TextField = new TextField ();
4 txtFld x = txtFld y = 20;
5 txtFld text = "Hello World!" ;
6 txtFld rotation = 45;
7 addChild (txtFld);
8
9 var tlfFld: TLFTextField = new TLFTextField ();
10 tlfFld x = tlfFld y = 100;
11 tlfFld text = "Hello World!" ;
12 tlfFld rotation = 45;
13 addChild (tlfFld);
Improved typographic controls
In many ways, the core of the Text Layout Framework is the TextFlow class (contained in the flashx.textLayout.elements package provided by Adobe) and its TextFlow markup syntax TextFlow markup is a bit like a cross between XML and HTML It’s structured like XML but has predefined tags and attributes, and controls display features Manipulating this class is your ticket to improved typographic control, columnar layout, and more
N OT E
TLF was first introduced to Flash
Professional users in beta format as
a component for Flash Professional
CS4 and to other ActionScript editors
(such as Adobe’s Flash Builder 4 and
Powerflasher’s FDT) via the beta
ver-sion of the Flex 4 SDK
At the time of this writing, it’s still
avail-able on Adobe Labs: http://labs.adobe.
com/technologies/textlayout/ However,
there is no guarantee that it will remain
available for Flash Professional CS4,
nor is it certain that the beta release is
stable enough to use in production
If you are interested in using TLF, we
recommend using Flash Professional
CS5, Flash Builder 4, or another editor
built around the release version of the
Flex 4 SDK.
Trang 7Although you can populate a TextFlow instance incrementally using string
input, it requires creating each paragraph, span, and so on individually with
a collection of classes and a fair amount of additional syntax Sometimes it’s
simpler to write the TextFlow content as one string containing markup
syn-tax, which is structured much like HTML Understanding the syntax is not
difficult, but explaining HTML-style syntax is outside the scope of this book
Unfortunately, no clear documentation of the TextFlow markup syntax
currently exists At the time of this writing, Adobe recommends an
under-standing of TextFlow markup tags (Table 10-3) to learn how to structure the
content and consulting the documentation of the TextLayoutFramework class
(http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flashx/
textLayout/formats/TextLayoutFormat.html) to learn how to lay out and
for-mat the content within the field
Table 10-3. TextFlow markup tags
div A division of text; can contain only div or p elements
p A paragraph; can contain any element except div
br A break character; text continues on the next line but does not start a new paragraph
a A hypertext link (anchor); can contain span, img, br, tab, and tcy elements
span A run of text in a paragraph; cannot contain other elements
tab A tab character; (not included in this chapter’s examples)
tcy A run of horizontal text, used within vertical text (such as Japanese) used, for example, to include English text
within Japanese text can contain the a, span, img, tab, or br elements; (not included in this chapter’s examples)
Figure 10-8 shows the hierarchical relationship among TextFlow elements,
which is also illustrated in the following sample markup structure
<div>
<p>
text<br />
<a>link text</a>
</p>
<p>
<span>text</span><br />
<img />
</p>
</div>
Div elements (div) can be used to organize copy into separate sections and
commonly apply block styling that might apply to multiple paragraphs
Paragraph elements (p) are used (unsurprisingly) to define discrete
para-graphs and contain paragraph-wide styling They need not be limited to text,
however It’s common, for example, to enclose images (img) or lists of links
(a) in paragraph tags, as shown previously Span elements are used to style
segments of a paragraph because they don’t force a line break Finally, if a
N OT E
See the post “Building a TLF TextFlow”
at the companion website for an example
of writing TextFlow content incrementally
TextFlow
p
p
br
div
div
Figure 10-8 Hierarchy of TextFlow
elements
Trang 8Text Layout Framework
line break (br) is desired, you can add them anywhere within a paragraph or link element
Table 10-4 describes a selection of TextFlow formatting options, all of which are used in the following example
Table 10-4. Select TextFlow formatting options
fontFamily Font family; can contain a comma-separated list of font families; the first font in the list found
will be used.
fontWeight Font weight; values include normal, bold, and inherit; applies only to device fonts, as
embed-ded fonts use one font family, including weight and style, per font symbol.
fontStyle Font style; values include normal, italic, and inherit; applies only to device fonts, as
embed-ded fonts use one font family, including weight and style, per font symbol.
typographicCase Case; values include default (mixed case), upper, lower, smallCaps, and inherit.
textDecoration Underline; values include none, underline, and inherit.
lineThrough Character strike-through; values include true, false, and inherit.
textAlign Text alignment; values include left, right, center, justify, start, end, and inherit; start
and end are designed to accommodate alignment in text that can be right-to-left or left-to-right; start represents left in left-to-right text and right in right-to-left text; end represents right in
left-to-right text and left in left-to-right text.
trackingRight Letter spacing in pixels or percent of font size (with % symbol), and inherit; number values for
both pixels and percent range from –1000 to 1000;.
textRotation Character rotation; values include rotate0, rotate90, rotate180, rotate270, auto, and
inherit.
lineHeight Leading in pixels (–720 to 720), percent of font size (–1000 to 1000, with % symbol), or inherit baselineShift Distance from baseline in pixels (–1000 to 1000) percent of font size (–1000 to 1000 with %
sym-bol), subscript, superscript, or inherit.
alignmentBaseline Aligns baseline of specified text to baseline; values include roman, ascent, descent,
ideo-graphicCenter, ideographicTop, ideographicBottom, useDominantBaseline, and inherit;
ideographic baselines used by Asian fonts; useDominantBaseline used when Asian fonts
enabled, determining baseline of text explicitly selected, not by paragraph See Figure 10-9.
top center bottom
ascent
roman descent
Figure 10-9 TLF text baselines
N OT E
Elements without a balancing closing
tag, such as img and br, must be applied
as self-closing tags to conform to XML
specifications This means you must add
a slash as the last character inside the
tag: <br />.
Trang 9The following code is found in the tlf_typography.fla source file It
demon-strates many of the most common formatting options used in a TextFlow
string, including some of those listed in Table 10-4 This example shows the
simplest way to apply a TextFlow string to a TLFTextField class instance
The field’s tlfMarkup property will automatically populate the field’s internal
TextFlow instance without first having to process the incoming string Figure
10-10 shows the outcome of this file
Figure 10-10 A TLF field formatted by a TextFlow markup string
1 import fl.text.TLFTextField ;
2
3 var tlfTxt: TLFTextField = new TLFTextField ();
4 tlfTxt x = tlfTxt y = 100;
5 tlfTxt width = 350;
6 tlfTxt multiline = true ;
7 tlfTxt wordWrap = true ;
8 tlfText selectable = false;
9 addChild (tlfTxt);
10
11 tlfTxt tlfMarkup = "<TextFlow xmlns='http://ns.adobe.com/
textLayout/2008' fontFamily='Arial' fontSize='18'><div><p>H<span
baselineShift='subscript' alignmentBaseline='descent'>2</
span>O, <span fontWeight='bold'>water</span>, <span typ
ographicCase='uppercase'>everywhere</span>,<br /><span
textDecoration='underline'>And</span> <span fontStyle='italic'>all</
span> <span color='#009900'>the</span> <a href='http://
en.wikipedia.org/wiki/The_Rime_of_the_Ancient_Mariner'>boards</
a> <span lineThrough='true'>did</span> <span fontSize='12'>shrink</
span>.</p></div><p textAlign='right'><span textAlpha='0.5'>Water,
water,</span> <span trackingRight='5'>everywhere</span>,<br
/><span lineHeight='150%'>Nor any drop to</span> <span
textRotation='rotate90' baselineShift='10'>drink</span> <img
width='10' height='16' source='water_drop.jpg' /></p></TextFlow>" ;
One side effect of this approach, however, is that the TextFlow instance is
tied to the field In the last example of the chapter, we’ll look at an
alterna-tive approach that creates an independent TextFlow instance first, and then
translates a string to populate it
Columnar layout
The following code, found in tlf_columns.fla, builds on the prior source file
Adding this code to the end of the prior example provides a simple
demon-stration of columnar layout Arranging TLF text in columns requires direct
N OT E
The text in this example is a modified excerpt of “The Rime of the Ancient Mariner” by Samuel Taylor Coleridge
N OT E
If when testing your file you get no errors but the text does not display, check the syntax of your TextFlow
string Look for single tags that are not self-closing (<br>, for example), tags that are not balanced (such as a <span>
with no </span>), incorrect or mis-spelled format properties, and improp-erly nested tags (such as text within a
<div> rather than within a <p> inside that <div>).
Trang 10Text Layout Framework
manipulation of a TextFlow instance In the prior example, however, working directly with a TextFlow instance was not required, thanks to the field’s tlf-Markup property This code demonstrates a simple way of gaining access to a populated TLF field’s TextFlow instance through its textFlow property:
12 //addition to previous example
13 import flashx.textLayout.elements.TextFlow ;
14
15 var tlfTextFlow: TextFlow = tlfTxt textFlow ;
16 tlfTextFlow columnCount = 1;
17 tlfTextFlow columnGap = 30;
18
19 stage.addEventListener ( MouseEvent.CLICK , onClick, false , 0, true );
20 function onClick(evt: MouseEvent ): void {
21 if (tlfTextFlow columnCount == 1) {
22 tlfTextFlow columnCount = 2;
23 } else {
24 tlfTextFlow columnCount = 1;
25 }
26 tlfTextFlow flowComposer.updateAllControllers ();
27 } Line 13 adds an import statement for the TextFlow class Line 15 creates
a TextFlow instance by referencing the field’s textFlow property All that remains is to set the columnCount and, optionally, the columnGap properties
In this example, a mouse click will change the column count at runtime to demonstrate the automatic reflow of text Line 16 sets the initial number of columns to 1, to match the appearance of the prior example Line 17 sets the gap between columns to 30 pixels This has no immediate effect on the layout
of the text
However, lines 19 through 27 create a mouse click listener and add it to the stage With each mouse click, the conditional beginning in line 20 checks the number of columns in the field and toggles between 1 and 2 columns Finally, Line 26 instructs the flow composer (which controls the flow of text)
of the TextFlow instance to update the text flow of the field Because the field
is already populated, the layout reflows between 1 and 2 columns on the fly Figure 10-11 shows the two-column layout of the file
Figure 10-11 The same TLF field from Figure 10-10, reflowed into two columns
N OT E
Although code is consolidated in this
book into logical blocks, import
state-ments can be moved to the top of the
collected script if you prefer This
option-al edit will organize option-all your import
statements in one place for clarity but
will not affect the file in any other way.