Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
105
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 18

Using an object to hold properties helps to explain the mechanics of the setStyle() method a bit. You’ll also notice that the style names are variants from the actual CSS1 subset. For example, whereas CSS1 calls for text-decoration: underline, Flash does not use dashes in such a way because it is interpreted as a minus operator. So, wherever you see a dash in a CSS style, remove the dash and capitalize the second word. You then have the Flash variant of the property name. For example, the style name text-decoration becomes textDecoration.

How to Define Tags, Class, and Proper ties

Now take a look at how you can set styles using straight CSS, which you can load into a StyleSheet object.

To set a tag definition, commonly known as a Selector definition, you simply do as you have seen previously in this chapter. For instance, the p selector affects only the p tag:

p {

font-size: 24;

}

In this example, all p tags in the document that associates itself with this style will display its text using a 24-pixel size font.

Alternatively, if you want to affect only a subset of tags, you can define a class instead:

.largeContent { font-size: 24;

}

Then, any tag that declares a class attribute as follows will show 24-pixel-high text:

<span class=”largeContent”>Some text.</span>

You can only use the class attribute in span and p tags.

You also can define multiple selectors on one style object. For example:

p, a {

font-family: Georgia;

}

This class will affect all <p> and <a> tags in the text field. Flash also allows the creation of custom selectors. For example:

p, someStyle, a { font-family: Georgia;

}

In this case, an HTML tag with the name someStyle will act essentially the same as the p tag. In this way you can create custom behaviors for custom tag names.

458

Handling Text

Pseudo-classes are supported on the <a> tag only. Only three pseudo-classes are supported:

a:link

a:hover

a:active

Properties are set as seen in the preceding examples, where each line between the opening and closing brackets contains one style property. Each property declaration contains a property name and a property value separated by a colon, and is terminated with a semicolon. CSS automatically treats all variable values as strings, so you do not need quotes on string values.

Using CSS with XML

Flash is fairly blind when it comes to text fields. It isn’t bound by any public specification, and works just fine with any tag name. Flash internally supports basic HTML tags that can have properties assigned directly to them via CSS. For example:

p {

font-family:Arial;

}

However, Flash accepts any string name for a node name class. For instance, you can make the following declaration to apply styling to a node with the name blogPostTitle, even though it is a tag that you invented and not part of any HTML specification:

blogPostTitle { font-family: Georgia font-size: 24;

}

After an XML node is declared, you can define it as follows:

<blogPostTitle>This is a title of a blog post</blogPostTitle>

All nodes with the name blogPostTitle will display the corresponding style.

It is important to remember that style sheets are cascading. This means that if an <a> tag exists within the blogPostTitle that doesn’t override the font-size, but only manipulates the color, the <a> tag will inherit the blogPostTitle properties, but retain any properties not redefined by the blogPostTitle selector.

The StyleSheet class allows the defining of new HTML tags for automated node name handling of XML, XHTML, and more. Take a closer look at this capability.

Try It Out

Load an XML File and Display It within a Text Field

For this example you should be familiar with XML and the XML class. The XML class is used briefly to load external XML data.

1.Open a new document in your favorite CSS file editor, and enter the following style definitions:

459

Chapter 18

blogPostTitle {

font-family: Georgia, serif; font-size: 24px;

}

blogPostTitleLink { color: #006699; font-size: 18px;

}

a:link {

text-decoration: underline;

}

2.Save the file as myXMLStyle.css in your workspace folder.

3.Open a new FLA and save it as xmlWithCSS.fla in your workspace folder.

4.Highlight the first frame, open the Actions panel, and enter the following code:

var id:Number = this.getNextHighestDepth();

var field1:TextField = this.createTextField(“field” + id, id, 20, 20, 300, 150); field1.wordWrap = true;

field1.multiline = true; field1.html = true;

var myStylesheet:TextField.StyleSheet = new TextField.StyleSheet(); myStylesheet.onLoad = function(success)

{

if (success)

{

for (var i in myStylesheet)

{

field1.styleSheet = this;

}

}

field1.htmlText = contentXML.toString();

};

var cssProxyLoader:LoadVars = new LoadVars(); cssProxyLoader.onData = function(str)

{

myStylesheet.onLoad(myStylesheet.parseCSS(str));

clearInterval(cssloadWatch);

};

var contentXML:XML = new XML(); contentXML.ignoreWhite = true; contentXML.onLoad = function(success)

{

if (success)

{

cssProxyLoader.load(“myXMLStyle.css”);

}

};

contentXML.load(“xmlContent.xml”);

460

Handling Text

5.Open a new document in your favorite XML editor (you might prefer to simply use Notepad) and enter the following XML:

<blogPostTitle>The quick brown fox! <blogPostTitleLink>

<a href=’www.some link’ >October 15th, 2005<a/> </blogPostTitleLink>

</blogPostTitle>

6.

7.

Save the document as xmlContent.xml in your workspace folder.

Test your code by selecting Control Test Movie.

How It Works

In this example you saw how the CSS class can be used to define custom tags that wrap the content. This can be extremely handy when formatting XML content because you don’t need to parse the node content to format it. So if a known XMLNode is known to be ready for display, except for its custom node names, you can easily define the style for those child nodes based on their node name.

This example also used the cascade mechanism inherent within cascading style sheets. The <a> tag was only defined, however, only with an underline. This causes all a tags within the document to display an underline. The <a> tag then inherited the properties defined in the blogPostTitleLink style because the a tag resides within that descriptive tag. Furthermore the blogPostTitleLink style inherited the font defined in the blogPostTitle style. In this way you can see how you can efficiently assign styles for a document without repeating declarations or creating many styles.

Also, the XML document was loaded before the style sheet document. Once the XML is loaded the XML onLoad event then kicks off the StyleSheet load event. You could also define a watch function to wait for each document to declare itself loaded and load them simultaneously.

Scroll Text Options

Flash has no built-in scroll bars. Content larger than the designated runtime stage size simply does not appear. In a browser, a page of text automatically presents scroll bars to find the content. In Flash, you must decide how to allow the user to scroll content.

Several ways exist to scroll a text field. Two components are available to accomplish the task: the ScrollBar component and the TextArea component. Each will automate the math involved with controlling a text field, but both are difficult to customize to a particular design style. The components use the same user interface behaviors as most operating systems and so are logical for the user.

A custom scroll bar should take into consideration usability and clarity of function. Many Flash applications will attempt to redefine the scroll bar’s behavior and how it works. This is successful in some cases, but is usually simply confusing and limiting for the user. If you decide to build your own scroll bar you should think carefully about the different behavior states your scroll bar is capable of, and what you are trying to achieve.

461

Chapter 18

Scrolling Text Using the TextArea Component

The simplest way to create scrollable text is to make use of the TextArea component. All you need to do is to drag a TextArea component to the stage, give it an instance name, and then assign text to the text property, as in the following line of code:

feedbackTextArea.text = “The quick brown fox jumped...”.

The component automatically adds the scroll bar if needed and allows the user to scroll through the text.

If you prefer, you can also place a TextArea component on the stage by having it in a movie clip in the library, and using attachMovie() to place a copy of the movie clip on the stage. You can also place an instance of the component on the stage directly using UIObject.createClassObject(), which you used in Chapter 9 and that you see in the following Try It Out.

A major drawback to the TextArea component is the inability to apply a TextFormat object to it. You must use the StyleSheet class when changing the look of text in the TextArea component.

Try It Out

Making a Scrollable Text Field with the TextArea Component

In this exercise you dynamically place an instance of the TextArea class on the stage, and then use that component to scroll text.

1.Open a new FLA and save it as textAreaTest.fla in your workspace.

2.First you’ll need to define the classpath for the TextArea. This is used by the UIObject class to instantiate a new instance of the class. Open the Actions panel and add the following code to the first frame:

import mx.controls.TextArea;

3.To make the assets for the class available within the library, open the User Interface section of the Component panel, select the TextArea component, and drag it to the library.

4.The component now appears in the Library. You can rename the library instance or place it within a folder for organization.

5.Enter the following code below the code you added in step 2:

var id:Number = this.getNextHighestDepth ();

var field2:MovieClip = createClassObject(TextArea, “field” + id, id);

6.Test the application to be sure it has access to the library instance and class package. Select Control Test Movie. You should see a small rectangular box in the top-left corner of the stage.

7.Now manipulate the size of the TextArea component. Close the SWF and return to the first frame ActionScript. Add the following code below the code you entered in step 5:

field2.setSize(400,150); field2.wordWrap = true;

field2.text = “Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum

Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum

462

Handling Text

Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem”;

8.Test the application by selecting Control Test Movie. The text field will now be much larger and display the text defined in the text property of the TextArea instance. The scroll bar appears within the boundaries defined in the setSize() method.

How It Works

In this example the TextArea component is used to rapidly introduce scrollable text into an application. This component is extremely handy but can be limiting. For example, the look of the component must be described by the global Style object. To make the TextArea instance transparent you can add the following code below the code added in step 7:

_global.styles.TextArea.backgroundColor = undefined;

This line of code will change all TextArea instances to display a transparent background. You can then individually set each background to a specific color while defaulting to transparent. In some cases this could be a limitation.

You can also customize the scroll bars or set the scroll bars to use a skin used by other components in your application. Refer to Chapter 11 for more information on skinning components.

The TextArea instance can be made to look and act as you want, but inconveniently requires its own set of methods to do so. As inconvenient as it can be to customize, the TextArea component is unmatched at displaying scrollable text extremely quickly. You might prefer to use the TextArea component when sketching out code and building prototypes or drafts of work.

Scrolling Text Using the ScrollBar Component

Another means of scrolling text is to use the ScrollBar component along with a standard text field. The ScrollBar component has a method called setScrollTarget() that links the ScrollBar instance with a text field. Once done, the thumb on the ScrollBar instance resizes to match the size of the text content, and manipulating the scroll bar controls causes the text to scroll. The setScrollTarget() method looks like the following, which links up a ScrollBar instance called descriptionScrollBar with a text field called descriptionTextField:

descriptionScrollBar.setScrollTarget(descriptionTextField);

This is one of the more popular ways to create scrollable text. It is a bit more compact in file size, it is quick to set up, and it enables you greater control over how text in the text field is formatted compared with the TextArea component. Try this technique next.

Try It Out

Making a Scrollable Text Field with the ScrollBar Component

This example uses a library font with a linkage name of myFont. If you don’t know how to do this, follow steps 2–8 in the First Try It Out section in this chapter. Alternatively, you can disable the font by removing the font declaration in the my_format object and remove the embedFonts setter of the field1 object.

463

Chapter 18

1.

2.

Open a new FLA and save it as scrollComponentTest.fla.

Highlight the first frame and enter the following code:

var my_format:TextFormat = new TextFormat();

my_format.font = “myFont”;// Requires an embedded font in the library my_format.size = 12;

var id:Number = this.getNextHighestDepth();

var field1:TextField = this.createTextField(“field” + id, id, 10, 10, 300, 150); field1.wordWrap = true;

field1.multiline = true; field1.antiAliasType = “advanced”;

field1.embedFonts = true; // Requires an embedded font in the library

field1.text = “Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem”;

field1.setTextFormat (my_format);

3.The code in step 2 simply adds a text field similar to the examples defined in earlier in the chapter. You can test the code by selecting Control Test Movie.

4.To make the field scrollable via the ScrollBar component you need to add the class package. Close the SWF and enter the following code below the code you added in step 2:

import mx.controls.UIScrollBar;

5.Now the assets for the component need to be added to the library. If you cannot see the Components panel, select Window Components. In the User Interface section highlight and drag an instance of the UIScrollbar component to the library. If you cannot see the library, select Window Library. The component is now ready to be called on to the stage.

6.Return to the Actions in frame 1. Add the following code below the code entered in step 4:

var id:Number = this.getNextHighestDepth();

var scrollbar1:MovieClip = createClassObject(UIScrollBar, “scrollbar” + id, id);

7.Test the code by selecting Control Test Movie. You should see a thin vertical rectangle in the top-left corner of the stage. This is the scroll bar. It doesn’t do anything yet.

8.Close the SWF and return to the ActionScript in frame 1. Add the following code below the code you added in step 6:

scrollbar1.setScrollTarget(field1); scrollbar1.setSize(20,field1._height); scrollbar1.move(field1._x+field1._width, field1._y);

9.Test the code by selecting Control Test Movie. You will now see the scroll bar in position and capable of scrolling text.

How It Works

In this example, a scroll bar was quickly created with the UIScrollbar component. By using the setScrollTarget() method of the component, the text field added in step 2 became scrollable within the user interface.

464

Handling Text

This method for scrolling text is a bit less limiting than using the TextArea component because the text field can retain its own properties and you can access them directly for manipulation of visual properties. You can customize the UIScrollbar component using the skin methods.

By using traditional text field creation methods found in Flash 5 and up, you can easily add the UIScrollbar to a text field created with the Text tool.

Another technique for scrolling text is to place a fixed-height text field within a movie clip and then move the movie clip, masking out the text that appears outside a defined area. The two previous methods (using the TextArea component and using a ScrollBar component) use the scroll property of the TextField class, whereas this technique moves the movie clip holding the text field. With the scroll property, the text field scrolls line by line; a movie clip can scroll smoothly, pixel by pixel. In some cases the class text scroll method is preferable, such as when performance is at a premium, but scrolling a movie clip will always appear smoother.

You have several ways to accomplish this example. One approach is to use a second movie clip as a mask. Flash 8 provides a new method called scrollRect()that gives you a way of scrolling a movie clip within a bounded area. The next Try It Out exercise shows you how to apply this method.

Try It Out

Bound and Scroll a Text Field with the scrollRect Method of the

 

MovieClip Class

This example uses a library font with a linkage name of myFont.

1.Open a new FLA, save it as scrollRectTest.fla, and enter the following code to frame 1:

import flash.geom.Rectangle;

var id:Number = this.getNextHighestDepth();

var viewArea:MovieClip = this.createEmptyMovieClip(“clip”+id,id); var area:Rectangle = new Rectangle(0, 0, 300, 150); viewArea.scrollRect = area;

The flash.geom package creates a rectangle object that is expected by the scrollRect property. This is simply facilitating scrollRect, to help you scroll some text.

2.Add the following code below the code you entered in step 1:

var id:Number = this.getNextHighestDepth();

var textHolder:MovieClip = this.viewArea.createEmptyMovieClip(“clip”+id,id);

var my_format:TextFormat = new TextFormat(); my_format.font = “myFont”;

my_format.size = 12;

var id:Number = this.getNextHighestDepth();

var field1:TextField = this.textHolder.createTextField(“field” + id, id, ; 10, 10, 300, 0);

field1.autoSize = true; field1.wordWrap = true; field1.multiline = true; field1.antiAliasType = “advanced”; field1.embedFonts = true;

465

Chapter 18

field1.text = “Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum

Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem Ipsum Lorem da dayem”;

field1.setTextFormat(my_format);

3.Test the code. Select Control Test Movie. The text is now bound to the rectangle defined in step 2. Try changing the rectangle size parameters defined in step 2.

4.Create a scroll bar from scratch instead of using a component by entering the following code below the code you added in step 2:

var id:Number = this.getNextHighestDepth();

var scrollbar1:MovieClip = this.createEmptyMovieClip(“clip”+id,id); var square:Number = 10;

scrollbar1.beginFill(0xCCCCCC,100); scrollbar1.moveTo(-square, -square); scrollbar1.lineTo(-square, square);

scrollbar1.lineTo(square, square); scrollbar1.lineTo(square, -square); scrollbar1.lineTo(-square, -square); scrollbar1.endFill();

scrollbar1._x = textHolder._x+textHolder._width+(scrollbar1._width/2); scrollbar1._y = textHolder._y+(scrollbar1._height/2);

5.Select Control Test Movie. You should see a gray square just the right of the text.

6.Close the SWF and return to the actions in frame 1. Add the following code below the code you entered in step 4:

scrollbar1.startPosition = scrollbar1._y; scrollbar1.onPress = function()

{

this.startDrag(false,this._x,this.startPosition,this._x, ; this.startPosition+this._parent.viewArea._height);

clearInterval(this.scrolling);

this.scrolling = setInterval(this, “scroller”, 10);

};

scrollbar1.onRelease = scrollbar1.onReleaseOutside = function ()

{

clearInterval(this.scrolling);

this.stopDrag();

};

7.Test the code. You can now move the scroll elevator up and down. It isn’t associated with your text yet, so it’s not actually scrolling anything, but you define that function next. Close the SWF and add the following code below the code you entered in step 6:

scrollbar1.scroller = function()

{

var percentPosition:Number = (this._y-this.startPosition) / this.maxSize;

textHolder._y = -(percentPosition * (textHolder._height - viewArea._height)); updateAfterEvent();

};

466

Handling Text

8.Test the code by selecting Control Test Movie. You can now use the gray square to scroll the text field.

How It Works

In this example you saw one way to mask text and use the properties of the movie clips to scroll the contents. The setMask() method could have been employed instead. The scrollRect() method is now the preferred method and presents a much more customizable and more efficient mechanism. If you have a habit of using setMask(), you should become familiar with scrollRect()and switch when using Flash 8.

First, a viewable area was defined using a movie clip viewArea with the scrollRect() method. This method employed a simple rectangle object to define the bounds which content within the view area are visible.

Next a content movie clip was created called textHolder. This is the actual movie clip whose y position is changed by the scroll button.

A classic text field was then created within the textHolder movie clip.

After the stage elements were defined, a scroll button was created using the movie clip object and the drawing API. This graphic could easily be replaced with an image or more complex vector graphics.

The mouse events were then defined that employed the startDrag() method as well as call a setInterval() method to smoothly scroll the content. Some simple math was calculated based on the height of the content and the height of the viewable area.

You can see that creating your own scroll elevator requires a bit of math and can be confusing to set up. Although it can be especially annoying if you have many scroll bars in your application, this method of scrolling the text field does have a nice smooth quality, and is easily skinned and customized.

The ease of customization in this method comes with a price. Because you defined the scroll elevator button it doesn’t quite act the same as an operating system button. It doesn’t resize according to the amount of content, and it doesn’t have up and down buttons at the top and bottom as most scroll bars do. Some users may find this difficult or even annoying. You should be careful when defining your own scroll methods. If possible you should emulate what the user expects as much as possible in regards to scrolling.

There’s one more scroll bar technique for you to explore. It makes use of TextField scroll property in conjunction with custom buttons. The buttons take the place of the ScrollBar component used earlier. Although this technique requires the most work, it also gives you the most design freedom.

Try It Out

Scroll Text Using the Scroll and maxScroll Properties

In this example you use a simple text field with wordWrap set to true, combined with a static field height. This method doesn’t require a mask. The exercise uses a library font with a linkage name of myFont.

467