Flash Camo (for short) is a graphics framework that allows AS 3 applications to be easily skinned from pngs, jpgs, or gifs. The framework is broken down into 3 core areas: Decals, the CSS Parser, and the CamoDisplay. These systems can be used individually or combined to fit your needs. When used together they form a powerful set of tools to help skin and style any Flash application. With Camo's modular approach, you can use as little or as much of the framework as you want. The entire framework is under 40k.
Flash Camo is open source (under the MIT License), is compatible with FlashPlayer 9/10, Flex 3, and AIR. It can be built with the open source Flex SKD compiler or used in Flash CS 3/4 as a SWC.
In this introduction we are going to use version 2.2 beta. You can check it out from Google Code here:
https://flash-camouflage.googlecode.com/svn/tags/FlashCamo_2.2.0_beta
I will introduce each of the major systems of the framework and at the end of each part there is a demo you can run to see the framework feature in action. Lets get started!
The main feature of the framework is the DecalSheet system (located in the camo.core.decal package); made up of the DecalSheetManager, DecalSheet and Decal classes. The DecalSheet concept was inspired by the decals you would get with model airplanes. Each model kit would contain sheets of graphics and on each sheet you could peal off a decal and place it on the model. Camo's version of the DecalSheet allow you to load in external images, cut out decals, and skin your application with the Decals. The following diagram will help when explaining the relationship between the three classes:
The DecalSheetManager (located in the camo.core.managers package) is the manager for the decal system. It handles the xml that defines a list of DecalSheet images and coordinates for cutting out each Decal. It also stores a collection of DecalSheets to make createing complex Decal look up tables easier to manage. You can configure DecalSheets and Decals on the DecalSheetManager at run time or with XML. Once this data is set, the DecalSheetManager goes out and gets all the images it needs for the DecalSheet images. Lets look at how to configure a DecalSheetManager with XML:
The above DecalSheet XML is broken up into two main nodes, one for Sheets (DecalSheets) and the other for Decals. Each Sheet node contains an name (unique reference name), preload (true or false), w (width) and h (height) attributes along with the src representing the path to file. You can add as many sheets as your application requires. Remember to only flag the critical ones for preloading to cut down on load time. The decals node defines how each decal should be cut out. A decal node has an name (unique name for lookups), sheet (name of the DecalSheet where Decal will be cut out from 1), x, y, w, and h.
To use this XML, simply call the DecalSheetManager's parseXML method. Once xml is parsed, the DecalSheet requests a list of all the sheet nodes flagged to be preloaded and begins loading the src images. The baseURL attribute, located in the sheets node, is added to the url of each page's src when making the load request. You can leave this empty and point each src directly to an absolute url if your images are not located in the same directory.
The DecalSheetManager makes use of a special loader class called the BitmapLoaderManager (located in the camo.core.managers package). Once the images are loaded, the DecalSheetManager is ready to be used. If a page is not flagged to be preloaded but is requested, it will be added to the load queue. Decals can still be requested before the DecalSheet images are fully loaded. The DecalSheetManager will use a Decal's width and hight to generate a proxy graphic (a temporary black placeholder graphic) that will be replaced once the corresponding DecalSheet has been loaded. The DecalSheetManager also makes use of the LoaderManagerEvent to dispatch updates on preload and regular loading progress. You can listen for preload next (LoaderManagerEvent.PRELOAD_NEXT), preload done (LoaderManagerEvent.PRELOAD_DONE), and load complete (LoaderManagerEvent.COMPLETE). You can use this to display load status as well as monitor the progress of preloading/loading of DecalSheet source images.
Loaded images get stored inside of a Dictionary within the DecalSheetManager as individual DecalSheets. Each sheet's key come from its name. At any time you can get a Sheet by calling getSheet on the DecalSheetManager. The DecalSheet uses the sample method for cutting out BitmapData from its source. When you request a sample, you must pass it a name that refers to a Rectangle defining the x, y, width, and height of the area to cut out. DecalSheets can be configured at run time without XML since a DecalSheet extends the Bitmap Class. Simply pass it a bitmap to use as the source image and use registerDecal on the DecalSheet to configure it at run time. Using a DecalSheetManager simplifies the process but DecalSheets and Decals can be used on their own whenever needed. Here is a diagram to illustrate the process:
A Decal is a Bitmap that contains a reference to the DecalSheet it was cut out from. Now that you have seen how we get xml data into the DecalSheetManager, lets talk about how to retrieve Decal instances. When you call getDecal on the DecalSheetManager or DecalSheet, you need to supply the name of a Decal. You can check if a Decal exists by looking through a DecalSheet's decalName Array. Once a Decal is requested, the Decal's name gets passed to the parent DecalSheet through the sample method and the Decal's BitmapData is returned inside of a new Decal Instance.
Since all Decals contain a reference to the DecalSheet it was cut out from, this connection allows the Decal to receive updates from its parent DecalSheet. You can change a DecalSheet's BitmapData at any time just as you would any other Bitamp instance. Decals listen for Event.CHANGE events from their parent Sheet and once an event is received, it resamples the DecalSheet and updates its own BitmapData 2. Imagine being able to reskin an entire application by changing the BitmapData in a single DecalSheet? Here is a diagram to illustrate how this works:
Changing the BitmapData of a DecalSheet will fire a CHANGE event telling all children Decals to update.
The following demo illustrates how a DecalSheet is displayed, including Decals defined on the Sheet, a quick demo of skinning a SimpleButton with Decals, as well as the ability to change the BitmapData of the DecalSheet with a new skin.
With Flash Camouflage's DecalSheet system, you can reduce your applications memory footprint by consolidating smaller images into larger sheets. Any graphic you would embed in a class or place in a FLA's library can be stored in a single DecalSheet or be spread over multiple Sheets depending on your needs3. Since DecalSheets can be set up to only load when requested, you can load in application graphics exactly when you need them; cutting down the initial startup and load time.
Camo's custom CSS parser, the CamoPropertySheet (found inside of the camo.core.property package), goes well beyond the native StyleSheet class by supporting style inheritance, pseudo selectors, and merging styles on the fly. The goal of the CamoPropertySheet is to make styles something you can apply to any of your classes instead of just TextFields. CSS is a great way to define your class's properties in an external file and Camo helps convert these css styles into property/value pairs you can apply to any Object.
Here is a simple CSS sheet:
/* This is a comment in the CSS file */
baseStyle {
x: 10px;
y: 10px;
width: 100px;
height: 100px;
padding: 5px;
margin: 10px;
}
baseStyle .Button{
x: 0px;
y: 0px;
background-color: #000000;
}
#playButton {
background-color: #FFFFFF;
background-image: url('/images/full_screen_background.jpg');
}
#fullScreenButton{
background-color: #FF0000;
background-image: url('/images/full_screen_background.jpg');
}
#playButton:over {
background-color: #333333;
}
interactive {
cursor: hand;
}
Once you have CSS that is ready to be parsed, either by loading it in from a URLLoader as text or by creating it as a string in your code at run time, you will need to call the CamoPropertySheet's parseCSS method. This method has one parameter, compressCSS. By default this is set to true. The parser requires your CSS to be properly formatted by removing all unneeded spaces, tabs, returns, px, and comments. There are two ways of doing this, you can use server side compression or let the CamoPropertySheet handle the compression for you. Here is what the compressed css would look like:
Once the CSS is parsed, you can retrieve an Array of selector names by calling the selectedNames getter. A selector represents the name of the particular CSS style and it's collection of values. The getSelector method will return the selector 4 and it's properties as a PropertySelector 5. New selectors can be added to the CamoPropertySheet by calling newSelector and passing a selector name and a PropertySelector instance. Finally, you can duplicate a CamoPropertySheet by calling the clone method 6.
Selector inheritance is also supported by the CamoPropertySheet. From the previous CSS sample, lets look at the .Button style. As you can see the selector name in the CSS is "baseButton .Button". Its formatting tells the parser that .Button inherits properties from baseButton. We refer to .Button as the subject and baseButton would be an ancestor element. If you were to call getSelector for .Button the parser will automatically return a PropertySelector with merged properties from baseButton and .Button. Any conflicting properties will be overridden by the subject style. Here is what the .Button object would look like:
{
selectorName: .BaseButton,
x: 0,
y: 0,
width: 100,
height: 100,
padding: 5,
margin: 10,
backgroundColor: #000000;
}
PropertySelectors created by the CSS parser have a reference to their selector name in the selctorName property. Also, it's important to note that in this example the x and y values from .BaseButton overrode the ancestor's values. In this case they are 0 and not 10 as defined in the baseStyle.
Class (.class) and ID (#id) selectors are supported by the CamoPropertySheet. There is no difference to the CSS parser between Classes, IDs, or regular selectors so when making a selector request it's important to understand how to join them. In CSS, the inheritance rules dictate that a Base Styles is overridden by a Class Style that in turn is overridden by the ID Style. You can simulate this by passing in multiple selector names when calling the getSelector method. If we wanted to create a "play" button style that inherits the default Button class style and the base interactive style we would call getSelector and pass in "interactive",".BaseButton","#playButton" using commas to separate each style name. By combining the names of each selector by lowest priority to highest priority the getSelector method will automatically parse out each selector and merge them into a single PropertySelector. The last selector name becomes the PropertySelector's selectorName value.
When Pseudo-Selector are requested, their parent style's properties will be added to the returned Object. Adding a colon (selector:pseudo-selector) to any style name will alert the parser that it needs to also inherit properties from the selector name to the left of the colon. In the above CSS example we request #playButton:over we will get back the following object:
{
styleName: #playButton:over,
backgroundColor: #333333,
backgroundImage: url('/images/full_screen_background.jpg')
}
In this example the background-color and background-image properties are inherited from the #playButton selector but since #playButton:over has its own background-color the ancestor's property is overridden.
It is important to keep in mind that there may be a performance hit when parsing large CSS files with lots of inherited selectors. Also, the compression used when parsing the CSS uses a complex RegEx pattern so it is better to do the compression on the server side instead of during run time. Outside of this limitation, the real power of the CSS parser comes into play when applying PropertySelectors to CamoDisplay classes.
The following demo illustrates how CSS text is parsed by allowing you to write your own css, valid selectors we become buttons under the Current Selectors area and you can preview selector inheritance in the Get Selector input field.
The CamoDisplay is the final building block of the framework and a powerful alternative to the native Sprite class. Before getting into the CamoDisplay we should take some time to talk about the AbstractDisplay and the BoxModelDisplay.
The AbstractDisplay handles the foundation for the BoxModel and CamoDisplay classes. Not only does it make public two methods, move and resize, but it also handles redraw and visual invalidation to optimize the graphic redraw for the display classes of the framework. The most important feature of the AbstractDisplay however is what happens when we call addChild and removeChild. The AbstractDisplay automatically creates a container called "display" that gets added as the first child to the display list. Every time another DisplayObject is added to an AbstractDisplay, it gets attached onto the class's display instance. All the display list methods are mapped over to the internal display Sprite. Here is a chart to illustrate the inheritance of Camo's display classes:
The BoxModelDisplay allows us to apply Margin, Padding, Border and a Background (Color/Image). The BoxModelDisplay manages the offset of the display sprite based on those properties. Lets take a look at how the Box Model gets rendered:
Camo's Box Model consists of a Margin, Border and Padding wrapped around a display.
Here is a list of supported properties of BoxModel:
CSS Property
Values
Example (px is stripped out by the parser)
background-alpha
"number range 0 - 1"
Example: background-alpha: .8;
background-color
valid hex color
background-color: 0xff0000; sets background red.
background-color: #ff0000; sets background red.
background-image
type filename
jpg, png, or gif
background-image: url (/imgs/sample_image.jpg); Will load in sample_image.jpg and redraw Box Model once loaded.
background-position
value for x y
background-position: 10px 30px; This only works if background-repeat is set to no-repeat.
background-repeat
"repeat no-repeat repeat-x repeat-y"
background-repeat: no-repeat; does not repeat the background image, can be used with background-position to move the image's x,y position.
background-repeat: repeat-x: Repeats the background image along its x value based on the height of the background image.
background-scale9
value for
x, y, width, height
background-scale9: 1px 1px 98px 48px; applies a scale9Grid to the background image.
border
or
border-top
border-right
border-bottom
border-left value for
size style color alpha
border: 1px solid #ff0000 .5; solid is the only style supported currently.
border-alpha
"value range 0 - 1" border-alpha: .5;
height value height: 50px;
margin
or
margin-top
margin-right
margin-bottom
margin-leftvalue for
top, right, bottom, left
margin: 5px 2px 2px 5px; applies values to top, right, bottom,left
margin: 5px 2px; applies 5 to top & bottom, 2 to right & left
margin: 10px; applies 10 to top, right, bottom, left. **Margin is not rendered, you must check its value when performing layouts with BoxMode/CamoDisplays**
padding
or
padding-top
padding-right
padding-bottom
padding-leftvalue for
top, right, bottom, left
padding: 5px 2px 2px 5px; applies values to top, right, bottom,left
padding: 5px 2px; applies 5 to top & bottom, 2 to right & left
padding: 10px; applies 10 to top, right, bottom, left
width
value
width: 100px;
A BoxModelDisplay's background-color and background-image work exactly to how it would in HTML. The background-color is the bottom most color behind the display. It is important to realize that the CSS width and height affect how the background fill will take place. If you do not define the width and height of the BoxModel, it will use the values from the display. The background-image gets composited on top of the background-color. The background-image property lets the box model know how to load in a source image 7. Background-images also have repeat rules: repeat (is default), no-repeat, repeat-x, repeat-y. When using no-repeat you can specify a background image's position (x, y) to offset the image. This is helpful when you only want a background-image to be displayed at a certain location behind the display.
When the BoxModelDisplay does a refresh 8, all of its values are reviewed and drawn to the graphic's layer of the BoxModelDisplay. This insures that the border, background-color, and background-image are a single Bitmap to save on memory. The display Sprite (where all children get added to) is offset by the top and left Padding, and Border 9. Once the refresh is complete the display will be correctly positioned. Padding is invisible unless you have set a background color or image. In that case, the background will show through in the area offset by the padding. When you request the width or height of a BoxModelDisplay the dimensions are returned taking into account the padding, border and display. The BoxModelDisplay can be used on its own but when combined with the CamoDisplay, you get additional css style support.
The CamoDisplay inherits some powerful layout logic from the BoxModelDisplay and introduces the applyProperties method. By passing a PropertySelector (obtained from a CamoStyleSheet) the CamoDisplay will attempt to apply the PropertySelector's values 10. This takes advantage of the PropertyApplierUtil and TypeHelperUtility that is part of the Property Managment System in Camo.
Here is a list of the properties supported by the CamoDisplay:
CSS Property
Values
Example (px is stripped out by the parser)
align
"left (default) center right"
align: left; the logic for this should be in another Class that extends the CamoDisplay or add's the CamoDisplay to its display list.
alpha
"value range 0 - 1"
alpha: .5; sets the alpha to 50%;
cursor
"hand pointer none"
cursor: pointer; this is a read only property. The actual logic to manage the cursor should be done in a class that extends the CamoDisplay.
overflow
"visible(default) hidden"
overflow: visible; any graphics outside of the display's css width and height will be displayed.
overflow: hidden; the display is masked off based on the style's width and height. If no width and height is set in the style the mask not work correctly.
rotation
number value
rotation:180; sets the rotation to 180.
scale9Grid
"values for x y width height"
scale9Grid: 1px 1px 98px 48px; applies a rectangle to the CamoDisplay's scale9Grid property.
vertical-align
"top (default) middle bottom"
vertical-align: top; the logic for this should be in another Class that extends the CamoDisplay or adds the CamoDisplay to its display list.
visibility
"visible(default) hidden"
visibility: hidden; sets visible to false;
x
number value
x: 10px; sets the x position to 10;
y
number value
y: 10px; sets the y position to 10;
z-index
number value
z-index: 5; This is supported in the CamoDisplay addChild is called.
The most important functionality added by the CamoDisplay is the rasterize method. Just like the BoxModelDisplay which draws its border, background-color, and background-image to the graphics layer, the CamoDisplay can do the same thing with its display Sprite. When you call rasterize, a Bitmap snapshot of the display is take, the old display is removed and a new one is put in its place with the previous display's BitmapData drawn to it's graphics layer. All the children that were attached to the display are removed (so the Garbage Collector can release them from memory) and you are left with a flattened display.
It is important to note that rasterize can only be called only once since all children in the display are removed. The speed and memory benefits can greatly increase the performance of your application. This also allows you to layer images in the display Sprite and then flatten them into a single image. Rasterize should be used on any CamoDisplay where its children will never be changed or used outside of the initial setup of the class. It is also an excellent technique to use when animating text.
The following demo illustrates all of the properties of the BoxModel.
Although the TypeHelperUtil (located in the camo.core.utils) does not belong to any one system in Flash Camo, it is key in converting string values from a PropertySelector into correctly typed data to be applied to your Class. The TypeHelperUtil contains a lookup table of functions to handle conversions of specific data types. Primitives such as Number, Array, and Object are built in. This is used as part of the applyProperties method in the CamoDisplay in conjunction with the PropertyApplierUtil. By default the TypeHelperUtil supports the following conversions:
Function Name
String Data Example
Description
stringToArray
one two three
This will convert any string into an array by splitting the spaces. This is based on CSS rules. You can override the default delimiter by calling the function directly.
stringToBoolean
true or false
Converts any true or false into a Boolean.
stringToDictionary
prop:value; prop2:value2;
Creates a Dictonary out of a string by splitting all elements by the semi-colen. The results are then split on the colon. Anything on the left of the colon becomes the property and the string to the right become the value.
stringToNumber
999
Converts any string into a number.
stringToObject
prop:value; prop2:value2;
Similar to how stringToDictonary work except the returned value is an Object.
stringToPoint
10 10
Creates a Point instance from a string using the space as a delimiter.
stringToRectangle
10 10 100 100
Creates a Rectangle instance from a string using the space as a delimiter.
stringToStyleSheet
style1{color: #ffffff}
Creates a StyleSheet from any string by taking advantage of the parseCSS method on Flash default StyleSheetClass.
stringToUint
0 or #000000 or 0x000000 or black
This will convert any string into a uint. It is primarily used to converts colors into uints. Color shortcuts are supported as well as CSS Style hex values.
stringToUrlRequest
url('path/to/anything')
Converts any string into a URLRequest. This method only uses the string inside of the url(''); Likewise you can leave the quotes out or use double quotes.
The TypeHelperUtil also supports color shortcuts when converting colors into uints. Here is a list of supported colors and their values:
Color
Preview
Value
Color
Preview
Value
Color
Preview
Value
black
0x000000
olive
0x808000
purple
0x800080
blue
0x0000FF
white
0xFFFFFF
teal
0x008080
green
0x008000
yellow
0xFFFF00
fuchsia
0xFF00FF
gray
0x808080
maroon
0x800000
aqua
0x00FFFF
silver
0xC0C0C0
navy
0x000080
magenta
0xFF00FF
lime
0x00FF00
red
0xFF0000
cyan
0x00FFFF
In addition to the built in string conversion methods you can register your own. The TypeHelperUtil has two methods for extending the functionality of the utility called registerFunction and removeFunction. You can also customize and extend the built in color support through the registerColor and removeColor as well. This allows you to add your own conversion based on your projects needs.
If you want to add your conversion functions you need to use the class's qualified name as the key. As an example to correctly convert a Point from a string, you would register your conversion function to flash.geom::point and not to a reference of the Point class itself. It is recommended that you register all custom functions in your doc class before you application gets started. If you are dynamically adding conversion functions that are specific to a particular section you should remove all unused function since they will not allow the Garbage Collector to remove your classes properly.
This covers a very in depth introduction to the Flash Camouflauge Framework. Like any framework there is a learning curve but hopefully these examples have shed a little light onto the mechanics going on behind the scenes. As always I am happy to answer any questions you may have by leaving a comment. Also, if you come across any bugs feel free to add it the the issues list on Google Code.
Footnotes:1 The framework handles looking up sheets by name so it should refer to the sheet's name defined in the xml. Sheet names should be unique to avoid conflicts.
2 The Decal's detach method will remove the connection to its parent DecalSheet.
3 When it comes to designing your decal sheets, you should group images that do not have transparency into single jpg or gif image. Images with transparency should be grouped together as pngs. Since pngs are larger, it helps to break these sheets up as small as possible in the order of importance. This will help cut down on load times and optimize the streaming in of your Sheets.
4 Multiple selector names can be passed into the getSelectors method. Simple separate selector names by commas. All of the selectors will be merged into a single PropertySelector instance based on the order they are supplied. The first selector would be the base and the following one would override any of the previous selectors values. See Classes and ID Selector section fro more information.
5 It's important to note that properties on PropertySelectors are strings. If you have numbers such as x or width in the CSS style they will have to be converted into numbers; this is discussed more the CamoDisplay section.
6 By default, calling clone() on a CamoPropertySheet will copy all of the styles in the StylesSheet but what if you only want to clone a few styles? You can pass in specific style names separated by a comma to be included in the duplicated PropertySheet.
7 The BoxModelDisplay supports jpg, png, or gif background images.
8 Calling the refresh method on a BoxModelDisplay is considered expensive and should only be used when needed.
9 Margin is not accounted for in offset of the display sprite unlike Padding. Instead Margin is a value accessible through the margin property and should be used by classes that layout or align BoxModelDeisplays.
10 Since PropertySelector values are strings, the PropertyApplyerUtil will attempt to use the source instance to determine what type each property should be converted to. The PropertyApplyerUtil supports String, Number, UINT, Point, URLRequest, StyleSheet, and Rectangle. See the TypeHelperUtil section for ways to added additional conversion logic.