The following code draws a horizontal line that’s 10 pixels wide and has five entries:A horizontal line with a gradient stroke Drawing rectangular and elliptical shapes The two most comm
Trang 1l Ellipse Draws an elliptical shape If its height and width are identical, it draws a circle.
l Line Draws a straight line from one set of coordinates to another
l Path Draws a shape based on a set of drawing commands, creating multiple shape segments
l Rect Draws a rectangular shape If its height and width are identical, it draws a square
The spark.primitives package also includes the following classes that are used to group graphics together and embed graphical files in conventional formats such as PNG, GIF, and JPG:
l BitmapImage A class that embeds bitmap data defined in a graphical file The file can
be in any one of the conventional bitmap file formats: PNG, JPG, or GIF
l Graphic A nonvisual class that can be used to group multiple FXG graphics together
When you place multiple FXG graphics within an instance of the Graphic class, they overlap each other using a layout architecture similar to a Group with a layout of BasicLayout
Drawing lines
The Line class draws a line on the screen As with all such primitives, it must be placed within a Spark application or component Its width and height properties determine its horizontal and vertical length, while the stroke property determines its color and style
The stroke property must be set to an instance of a class that implements the IStroke face Examples of such classes in the Flex 4 SDK include GradientStroke and
Using gradient strokes
As with the fill property used with shapes that are drawn with the Rect, Ellipse, and Pathclasses (described in the following sections), the stroke property can be set to a gradient of two
or more colors with the GradientStroke class or with one of its subclasses, LinearGradientStroke and RadialGradientStroke
Trang 2The gradient stroke classes support a property named entries that’s set to an array of two or more instances of the GradientEntry class The following code draws a horizontal line that’s 10 pixels wide and has five entries:
A horizontal line with a gradient stroke
Drawing rectangular and elliptical shapes
The two most commonly used primitive vector graphic classes are Rect and Ellipse Respectively, they render rectangular and elliptical shapes on the screen Both support fill and stroke prop-erties, which enable you to define the outer border and inner fill of the shape you’re drawing
Each shape’s fill property can be set to an instance of a class that implements the IFill face Examples of such classes in the Flex 4 SDK include:
inter-l BitmapFill
l LinearGradient
l RadialGradient
l SolidColorAnd, as described in the previous section on the Line class, each shape’s stroke property is set
to an instance of a class that implements the IStroke interface
Trang 3All shape classes support the x, y, top, bottom, left, right, horizontalCenter, and verticalCenter
properties to control a shape’s position within its container, and the height and width properties to control its dimensions As with all Flex visual components, the height and width can be set either to a numeric value representing a certain number of pixels or to a percentage value n
The following MXML code defines a rectangle with dimensions of 400 pixels width by 300 pixels height The rectangle’s outer border is a solid black line with a weight of 2 pixels, and the fill is a solid light gray:
<s:Rect width=”400” height=”300”
This simple shape is defined as an instance of the Rect class
Drawing arbitrary shapes with the Path class
The Path class enables you to declare any shape based on a set of commands that replicate the features of the Flash drawing API Its data property is a string that executes cursor placement and drawing operations The data string alternates commands and sets of numeric values Each com-mand is notated with a single alphabetical character, as follows:
Trang 4l C Draw a cubic Bezier curve The first two values are the first set of control coordinates,
the second two values are the second set of control coordinates, and the last two values are the drawing destination
l H Draw a horizontal line from the current cursor coordinate to a new X coordinate.
l L Draw a line from the current cursor position to a set of coordinates For example, the
command L 100 100 causes a line to be drawn from the current cursor position to X and
Y coordinates of 100 and 100
l M Move the cursor to a set of coordinates For example, the command M 50 100 causes
the cursor to be placed at an X coordinate of 50 and a Y coordinate of 100
l Q Draw a quadratic Bezier curve The first two values are the control coordinates, and the
last two are the drawing destination
l V Draw a vertical line from the current cursor coordinate to a new Y coordinate.
l Z Close the path.
The following simple Path object draws a horizontal line starting at X and Y positions of 100, and then draws a horizontal line to an X position of 500 The color and weight of the path are deter-mined by its stroke property:
cur-property of M100100h500Z creates a horizontal line that’s 500 pixels wide, starting at an X position of
100, whereas if you use the uppercase H, the line is 400 pixels wide (drawn from 100 to 500 pixels) n
Trang 5<s:GradientEntry color=”0x000000” alpha=”0.8”/>
<s:GradientEntry color=”0xFFFFFF” alpha=”0.8”/>
Adding visual effects
The primitive vector graphic classes support many properties that enable you to modify their appearance Examples include gradient fills and strokes, drop shadows and other filters, and scal-ing, or resizing, of vector graphics In this section I describe some of the most commonly used effects from which you can choose
Using gradient fills
The fill property that’s supported by the Rect, Ellipse, and Path classes can be set to a solid color with the SolidColor class or to a gradient with either RadialGradient or LinearGradient Each does exactly what its name implies:
Trang 6l LinearGradient Defines a change in colors in a linear using calculation from one dinate to another By default the gradient is calculated from left to right, but it can be adjusted by changing the gradient class’s direction property; for example, to change the gra-dient to go from top to bottom, change the LinearGradient object’s direction to 90.
coor-l RadialGradient Defines a change in colors starting from the certain point in an object (by default its center) and radiating outward to its borders You can set the focalPointRatio and rotation properties to change the point from which the gradient radiates
The application in Listing 14.1 defines two Ellipse shapes The first uses a radial gradient, and the seconds uses a linear gradient Each is modified by the focalPointRatio and rotationproperties to create a particular visual appearance
<s:Label text=”Radial Gradient”/>
<s:Ellipse width=”200” height=”100”
<s:Label text=”Linear Gradient”/>
<s:Ellipse width=”200” height=”100”
horizontalCenter=”0” verticalCenter=”0”>
Trang 7The code in Listing 14.1 is available in the Web site files in the chapter14 project as GradientDemos.mxml n
Figure 14.4 shows visual result: two Ellipse objects with different types of gradient fills
Trang 8<s:Path data=”M 0 40 L 40 0 L 105 0 L 144 40 L 144 51
L 105 90 L 40 90 L 0 51 L 0 40 Z “>
<s:fill>
<s:RadialGradient>
<s:GradientEntry color=”#333333” ratio=”0” alpha=”1”/>
<s:GradientEntry color=”#CCCCCC” ratio=”0.09” alpha=”1”/>
<s:GradientEntry color=”#333333” ratio=”0.37” alpha=”1”/>
<s:GradientEntry color=”#CCCCCC” ratio=”0.89” alpha=”1”/>
<s:GradientEntry color=”#333333” ratio=”0.99” alpha=”1”/>
Reusing graphic elements with <fx:Library> and <fx:Definition>
The Flex 4 SDK adds a new MXML element named <fx:Library> that you use to define graphic elements that can then be reused anywhere in the same MXML document Within the
<fx:Library> element, you define one or more <fx:Definition> element Each
<fx:Definition> describes a graphic element
Caution
The <fx:Library> tag must be placed as the first child element within the MXML document’s root element
If you place any other tags before it, a compiler error is generated n
The application in Listing 14.2 defines a single vector graphic as a library definition Its name is set
as CurvedArrow In the body of the application, there are three instances of the graphic Each sets its scaleX and scaleY properties to a different value The resulting application displays three instances of the arrow Even though they’re different sizes, they all show clean curves and smooth gradient fills
Trang 9<s:GradientEntry color=”0x000000” alpha=”0.8”/>
<s:GradientEntry color=”0xFFFFFF” alpha=”0.8”/>
<s:HGroup horizontalCenter=”0” top=”20”>
<fx:CurvedArrow scaleX=”1” scaleY=”1”/>
<fx:CurvedArrow scaleX=”2” scaleY=”2”/>
<fx:CurvedArrow scaleX=”4” scaleY=”4”/>
is a direct child of <s:Application> It contains this definition:
Trang 10docu-Scaling graphic elements
An MXML graphic is rendered as a vector graphic; this means that its rendering is calculated ematically rather than as a set of pixels (as is the case with bitmap graphics) As a result, you can
math-increase or decrease the size of the graphic (a process known as scaling) without disturbing the graphic’s resolution When you do the same thing with a bitmap graphic, it’s often pixilated, show-
ing jagged edges With vector graphics, the rendering stays clean and attractive
In Listing 14.2, the graphic that’s defined in the <fx:Library> section is rendered three times, each time with a different value for the object’s scaleY and scaleY properties:
<fx:CurvedArrow scaleX=”1” scaleY=”1”/>
<fx:CurvedArrow scaleX=”2” scaleY=”2”/>
<fx:CurvedArrow scaleX=”4” scaleY=”4”/>
Figure 14.6 shows the result, with the three versions of the arrow graphic displayed side by side
Notice that the graphic’s curves are smooth regardless of the scale This is a benefit of vector ics: because their presentation is calculated mathematically, they can adjust to whatever scale your application needs
FIGURE 14.6
A graphic element displayed in three scales
Trang 11Applying filters
Each of the primitive vector graphic classes supports the filters property, an array of objects derived from one of the classes in the spark.filters package The following filter classes are included in the Flex 4 SDK:
<s:GradientEntry color=”0x000000” alpha=”0.8”/>
<s:GradientEntry color=”0xFFFFFF” alpha=”0.8”/>
Trang 12graphi-Creating FXG graphics with Creative Suite software
Starting with Creative Suite 4, Adobe added features to Photoshop, Illustrator, and Fireworks that enable you to create and export graphics in FXG format The resulting files can be used in your Flex applications as embedded graphics
Creating FXG graphics with Photoshop
Adobe Photoshop is primarily used to create and manipulate bitmap graphics, so it might seem at first like FXG wouldn’t be useful to Photoshop developers However, wrapping bitmap files in FXG gives you a very easy and convenient way of exporting a graphic in a format that can be used as an ActionScript class in your Flex applications
Follow these steps to export a Photoshop file as FXG:
1 Open the file in Photoshop.
2 Choose File ➪ Save As.
3 Set the Format to FXG (*.fxg).
4 Select the folder in which you want to create the file.
5 Set the filename using the .fxg file extension and click Save.
A sample FXG file built in Photoshop might look like this:
Trang 13repeat=”false” d:locked=”true” d:userLabel=”Background”/>
<BitmapGraphic width=”400” height=”300”
To use this file in your Flex application, create the FXG file and its associated assets folder where in your Flex project’s source-code root folder
any-Creating FXG graphics with Illustrator
Adobe Illustrator is primarily designed to enable the creation of vector-based graphic art While designers can work with bitmap formats in Illustrator to some extent, they typically move to Adobe Photoshop when building graphics that are primarily bitmap-based
Starting with Illustrator CS4, users can save their vector graphic files in FXG format In Illustrator CS4, the resulting files are in FXG 1.0, while in Illustrator CS5, the format is updated to FXG 2.0 Regardless
of the version, you can use the resulting FXG files in Flex 4 applications in a number of ways
Figure 14.8 shows a vector graphic in Illustrator CS4 The graphic was created with a variety of Illustrator tools, including a simple rectangular shape
To create an FXG file in Illustrator that describes this shape and can be used in Flex 4, follow these steps:
1 Create or open a file in Illustrator.
2 Choose File ➪ Save As.
3 In the Save As dialog box, set the Save as type option to FXG (*.fxg) and assign a
file name with an extension of .fxg.
4 Click Save
5 In the FXG Options dialog box, shown in Figure 14.9, set any desired options.
6 Click OK to save the file.
Trang 15Listing 14.3 shows the contents of the resulting FXG file The XML markup in the file describes the vector graphic in mathematical terms and includes metadata that’s used by Illustrator to parse and enable later modification of the file.
LISTING 14.3
An FXG file created by Illustrator CS4 that describes a shape with a gradient fill
<?xml version=”1.0” encoding=”utf-8” ?>
<Graphic version=”1.0” viewHeight=”367” viewWidth=”247.5”
ai:appVersion=”14.0.0.367” d:id=”1” xmlns=”http://ns.adobe.com/fxg/2008”
<fill>
<RadialGradient x=”77.084” y=”125.323” scaleX=”582.81”
scaleY=”582.81”>
<GradientEntry color=”#ffffff” ratio=”0”/>
<GradientEntry color=”#231f20” ratio=”1”/>
<ai:DictEntry name=”includeXMP” value=”0” valueType=”Boolean”/>
<ai:DictEntry name=”writeImages” value=”1” valueType=”Boolean”/>
continued
Trang 16LISTING 14.3 (continued)
<ai:DictEntry name=”aiEditCap” value=”1” valueType=”Boolean”/>
<ai:DictEntry name=”versionKey” value=”1” valueType=”Integer”/>
<ai:DictEntry name=”includeSymbol” value=”0” valueType=”Boolean”/>
<ai:DictEntry name=”preserveTextPolicy” value=”3”
<ai:Artboards originOffsetH=”58.5” originOffsetV=”595.5”
rulerCanvasDiffH=”306” rulerCanvasDiffV=”-396” zoom=”1.5”>
<ai:Artboard active=”1” bottom=”228.5” index=”0” left=”58.5”
<ai:Stroke colorType=”ThreeColor” miterLimit=”4” weight=”1”>
<ai:ThreeColor blue=”0.125” green=”0.122” red=”0.137”/>
<ai:GradientStop colorType=”ThreeColor” rampPoint=”0”>
<ai:ThreeColor blue=”1” green=”1” red=”1”/>
</ai:GradientStop>
<ai:GradientStop colorType=”ThreeColor” rampPoint=”100”>
<ai:ThreeColor blue=”0.125” green=”0.122” red=”0.137”/>
</ai:GradientStop>
</ai:GradientStops>
Trang 17</ai:Gradient>
</ai:Fill>
<ai:ArtStyle>
<ai:LiveEffects>
<ai:LiveEffect index=”0” isPre=”1” major=”1” minor=”0”
name=”Adobe Punk and Bloat”>
tag This folder must be copied along with the FXG file into your Flex project in order for the graphical element
to be rendered correctly n
Creating FXG graphics with Fireworks
Adobe Fireworks CS4 is a hybrid graphics editing product that deals well with both bitmap and vector graphics When you create a graphic from scratch with Fireworks, and primarily use its vec-tor graphic tools, the resulting artwork can be exported as a pure FXG file that can then be used in
a Flex 4 application
Figure 14.10 shows a vector graphic created in Fireworks CS4 This is the same graphic element that was originally created in Illustrator; I show it here to make the point that you can create simi-lar vector art in both products
To save the vector graphic in FXG format, follow these steps:
1 Choose Commands ➪ Export to FXG from the Fireworks menu.
2 In the Select Folder dialog box, select the folder in which you want to save
the FXG file.
3 Enter the filename of the FXG file you want to create and click OK.
Trang 18FIGURE 14.10
A vector graphic in Fireworks CS4
Listing 14.4 shows the contents of the resulting FXG file created by Fireworks CS4
<Group id=”Page_1” fw:type=”page”>
<Group id=”State_1” fw:type=”state”>
<Group id=”Layer_1_1” fw:type=”layer”>
<Group id=”undefined”>
Trang 19<Path winding=”evenOdd” data=”M 173 186 C 269 318 203 425 121 270
<GradientEntry color=”#ffffff” ratio=”0” alpha=”1”/>
<GradientEntry color=”#ffffff” ratio=”0.01” alpha=”1”/>
<GradientEntry color=”#231f20” ratio=”0.99” alpha=”1”/>
<GradientEntry color=”#231f20” ratio=”1” alpha=”1”/>
Using FXG files in Flex applications
Once you’ve created your FXG files with Photoshop, Illustrator, or Fireworks, you can embed them in a Flex application in a couple of ways:
l Use the <s:BitmapGraphic> tag to embed an FXG graphic with the @Embed()compiler directive
l Treat FXG files as ActionScript classes and instantiate them with both MXML and ActionScript code
Trang 20Unlike the FXG ActionScript classes that I described earlier in this chapter, graphics that are drawn with FXG files cannot be modified at runtime by changes to its properties If you need your FXG graphic to be modifiable
at runtime, consider copying and pasting the FXG code from the file into an MXML document n
Embedding FXG graphics with <s:BitmapImage>
The <s:BitmapImage> tag is used in Flex 4 MXML files to embed graphical elements as maps To use this strategy, set the tag’s source attribute to the name and location of the FXG file, wrapped in the @Embed() compiler directive:
bit-<s:BitmapImage source=”@Embed(‘fxgGraphics/FWGraphic.fxg’)”/>
Caution
When you embed an FXG graphic in this fashion, the vector graphic is transcoded at compile time into a map graphic As a result, if you then try to scale the graphic, you might see pixilation and other artifacts nor- mally associated with bitmap graphics n
bit-Using FXG files as ActionScript classes
You can also use FXG files as ActionScript classes, instantiating and placing them in your tions using either MXML or ActionScript code
applica-To add an FXG file as a graphical element with MXML, first declare a custom namespace in the MXML document that associates an XML prefix with the folder (package) in which the FXG file is stored:
<fxgGraphics:MyFXGGraphic click=”fwgraphic1_clickHandler(event)”
buttonMode=”true”/> n
Trang 21If you prefer, you can use ActionScript code to declare, instantiate, and place an instance of an FXG graphic in your application The application in Listing 14.5 creates and places an FXG graphic on the screen upon application startup It then sets various properties and event handler
to use the graphic as a lightweight button
protected function application1_creationCompleteHandler(
event:FlexEvent):void {
Alert.show(“You clicked the graphic”, “Alert”);
} ]]>
Trang 22In this chapter, I described tools that help you debug a Flex application You learned the following:
l FXG is an XML-based markup language that is used to describe vector graphic elements and embed bitmap graphics
l The Flex 4 SDK includes ActionScript classes in the spark.primitives package that reproduce the effect of their equivalent FXG elements and mimic their syntax when declared with MXML
l You can use the primitive vector graphic classes to declare vector graphics in MXML or instantiate and add them to your Flex application at runtime with ActionScript
l Adobe Photoshop, Illustrator, and Fireworks can import and export FXG files
l FXG files can be embedded in Flex applications as bitmap graphics
l FXG files can be treated as ActionScript classes in Flex applications
Trang 23Skinning Spark Components
IN THIS CHAPTER
Declaring skins as MXML components
Using skin states and skin parts Binding custom skins to Spark components
Making copies of existing custom skins
Customizing component appearance with graphic elements
As I described in Chapter 14, one of the Flex 4 SDK’s most important
new features is the capability to redefine the appearance of visual
controls with programmatic skins.
In past versions of the Flex SDK, you could create your own skin as an ActionScript class By overriding certain methods that are called at runtime from the Flex framework and using the Flash drawing application program-ming interface (API) to declare vector graphics, you could define an entire visual presentation without ever using graphical applications like Adobe Photoshop and Illustrator
This strategy, however, was slow and cumbersome And, because the cal applications I’ve mentioned couldn’t interpret the ActionScript code and show you a preview of its results, you had to use your imagination (and a lot
graphi-of graph paper) to figure out how to code the image you wanted to create
In Flex 4, skins are now defined as MXML components that are extended from new classes named Skin and SparkSkin You can bind the skin component to an application or custom component at compile time or run-time with its skinClass style The skin class can be constructed with a combination of vector graphics, bitmap graphics, and Flex components to achieve whatever design ideas your application requires
Trang 24In this chapter, I describe how to define custom skins using the new MXML architecture, and then how to attach them to your applications and custom components.
On the Web
To use the sample code for this chapter, import the chapter15.fxp Flex project archive file from the Web site files into your Flash Builder workspace n
Creating and Using Spark Custom Skins
A custom skin component for a Flex 4 application or any of its Spark components is based on the new Skin and SparkSkin classes You can start either by creating a new copy of a component’s default skin class (a step made very easy by Flash Builder 4) or you can create a new fresh compo-nent that extends the Skin class While it’s possible to create such components in either MXML or ActionScript, most developers find that the MXML approach is much easier and the resulting code far more readable
Skinning a Spark application
You can create a new custom skin using the new architecture for any component that includes the new SkinnableComponent class in its inheritance hierarchy SkinnableComponent extends UIComponent, which means that Spark components can be added as display children of any Spark or MX containers
In this section, I describe how to create a new custom skin for the Spark Application nent, but most of the techniques also apply to all other Spark components
compo-Creating a custom skin
To create a new custom skin, start by creating a new custom MXML component As with all MXML components and ActionScript classes, I recommend that you place your custom skins in a specially named package under your Flex project’s source-code root folder
If you’re using the Flex project that’s available for download from the Web, you’ll see that it already has a package named skins under the source-code root folder If you’re working on your own Flex project, you’ll need to create this new package:
1 Open the Flex project in Flash Builder.
2 Right-click the default package in the Package Explorer view and choose New ➪
Package.
3 As shown in Figure 15.1, name the new package skins.
4 Click Finish.
Trang 25FIGURE 15.1
Creating a new package in the Package Explorer
Next create a new skin component:
1 In the Package Explorer, right-click the new skins package and choose New ➪
MXML Component.
2 In the New MXML Component dialog box, shown in Figure 15.2, type
CustomAppSkin in the Filename field.
3 Accept the Layout default value of None.
4 Click the Browse button next to Based on.
5 Select spark.skins.SparkSkin and click OK.
6 Delete the default values in the Width and Height settings
7 Click Finish to create the new skin component.
The code for the new skin component looks like this: