Flash Friday - AS3 Signals Basics
A short while back I mentioned a couple new open source projects I started working with at my new job. One of those projects was AS3 Signals. Since I've begun using it I've really grown to like it and I wanted to explain why. Hopefully my explanation of why will also include enough of the how. First off, have been a big fan of the AS3 event model since it came out with flash player 9. It, like many other AS3 updates, was much cleaner than the ways we were doing things in AS1/2. However, there have always been a few things that have bugged me just a little about the native event model.
I have to look at documentation to see what events a class object fires.
I can't count the number of times I am looking into a new framework, or even native classes, and I hope it fires an event but I can't just tell by code completion alone. Worse yet, sometimes important events don't even get documented so I have to search through source code to see what gets dispatched. On the flip side, if I'm writing custom classes I don't like writing documentation. I like my code to be readable like a good book, if at all possible. The AS3 event model forces you to read and write documentation. How could AS3 Signals clear up this problem though?
AS3 Signals clears up the problem of needing the documentation by having you create individual signals as objects in a class. This allows the programmer the opportunity to name the signal appropriately, thus making it easy to understand for the user of this class. Thus eliminating the requirement for documentation.
Let's give a simple example. Let's say you have a class that loads an external file and isn't ready until that file is loaded and parsed. With AS3 Signals this is a relatively simple process.
First create the signal in the class:
public var becameReady:Signal; public function MyFileLoader( url:String ):void{ becameReady = new Signal(); // you can come up with your own code here. }
Now anyone wanting to use the MyFileLoader class can see that you have a signal called becameReady. Hopefully they can tell from just that info what it does. Or perhaps you can come up with better naming. Either way this is an improvement.
Event types are strings
Strings are flexible and easy to read ( such as in a trace or error message ). The other problem is that they are not type safe and I've had times where event type naming collisions do happen. AS3 signals takes care of this problem by both solving and circumventing the problem.
AS3 Signals circumvents the problem by having you create separate ISignal objects for each type of event you would have dispatched in the past. Even though they are all of type ISignal, they are each distinct fields on an object. For example, if I had a class controlling a form, some of its signals might look like this:
public var submitClick:NativeSignal; public var clearClick:NativeSignal; public var completed:Signal;
AS3 also solves the problem by having event type checking, if you are working with the native event model. I haven't worked much with this at this point so I won't get into this in this article. If you'd like to know more about this comment below and I can write about it in a future article.
Custom events and event dispatcher classes take too much code for the simplest task
We've all been there, we want to make a custom events for a project but we have to write a whole new class to encapsulate what we need. Also, if we want to dispatch these events from a class that doesn't extend EventDispatcher we need to make sure to implement IEventDispatcher. Sure, these are relatively simple tasks but they take time and you are writing code that reeks of duplication.
As you have seen above, it is really simple to create a "custom" signal. Just define and initialize a new signal. Dispatching it is just as easy.
public var somethingHappened:Signal; private function init():void { somethingHappened = new Signal(); } private function doSomething():void { // custom code that does something ;) somethingHappened.dispatch(); }
Too make the signal more custom you can send as many objects as you want in the dispatch call. I'll leave that as an exercise for the reader ( or you can exercise the comments section and I'll show you what I mean below ).
If you just want to listen once you have to write extra code
The native event model doesn't make it easy to listen once. Perhaps you want to listen to a view's close button for just one click. With the native event model you have to remember to call removeEventListener in you event handler or else your program may not work as expected and it will likely create a nasty memory leak. AS3 Signals simplifies the process with the addOnce() call.
private function init():void { doSomething(); view.closeButtonClick.addOnce( onCloseButtonClick ); } private function onCloseButtonClick(){ view.close(); }
The previous addOnce call was so minor you might not have noticed it in the code. Really, that's all it takes. Signals are really quite easy to clean up.
Cleaning up listeners is difficult
When trying to find memory leaks, the first thing I look for is calls to addEventListener. They are usually the major culprit because it is so easy to lose track of which listeners were added to an object and for which event type. As you saw above, Signal objects have a built in mechanism for removing listeners after a single call if you want. They also have a simple way to remove all listeners from themselves, the aptly named removeAll function.
function close():void { closeButtonClick.removeAll(); otherSignal.removeAll(); }
Conclusion
This article was much longer than I thought it would be. If you made it this far, thank you for reading. I hope you see how AS3 Signals is an improvement over the native event model. Once you start using Signals you'll likely find yourself using events less and less. The event model is still core to AS3 though so there are some good ways to use them together. I plan to write a ( hopefully shorter ) article on using AS3 Signals with the native event model in the future. If you have any questions, comments or requests regarding AS3 Signals please let me know in the comments below.
Robotlegs and Signals
Just a short note for this, the first Flash Friday post of 2011. Just last week I started a new job in the social game space. It is a very exciting opportunity to work with some new people and learn new things. One thing to learn is the code base that they use, some which is open source. Two OS projects that I am now working with that I've never worked with before have caught my eye. These two projects are Robotlegs and Signals. First there is Robotlegs, an MVCS framework that is similar to PureMVC but if you've used any MVCS framework ( such as Cairngorm ) the concepts are similar. Robotlegs is cool because it does a really good job of keeping classes well decoupled through the use of metatags and injection. If you code any games or rich internet applications with flash I highly recommend giving it a look to see what you can use from it.
Second is AS3 Signals. Signals is an Observer pattern framework that you can use instead, or in conjunction with, the actionscript event model. I've been a fan of the observer pattern for a while, using the AsBroadcaster class back in AS2. When AS3 came around I relished in its event model, not because it was perfect but because it was better than using AsBroadcaster ( or rolling your own setup ). Signals improves upon some of the shortcomings of the AS3 event model in a few different ways.
All in all these are the two big new frameworks I am using at my new gig and I plan to share some lessons as I learn them. There is also much more that I'll learn about as well and I plan to share them as well. For now, check out Robotlegs and AS3 Signals and see what bits of them you can use or just get some good ideas for your own code. I hope if you do you'll share them in the comments.
Have you used either of of these frameworks? What do you think? Any gotchas you need to watch out for? I'd love to hear what you've encountered in the comments below.
The molehill that is a mountain: 3d flash APIs
Last year around this time I wrote about what 2010 would bring in the world of flash. Write now I want to talk about one specific change that seems to be coming in 2011 - project:Molehill ( 3d APIs for flash Player ). The following video ( if you are viewing this on a flash capable device ) is from the announcement at this year's Adobe Maxx event.
For me this is quite exciting. Back when I worked at Provis we talked a lot about using 3D for web interfaces. Because we we're a video heavy agency we even had a 3D person on staff and we experimented with different libraries from time to time. Unfortunately, not much came of it as it never seemed worth the time investment to change our pipeline that much.
Now I work in the social media game space and true 3D in flash with decent performance opens up a whole new realm of games for social media. It does this just in time. Social media gamers are becoming mature gamers fast and will demand a better experience sooner, rather than later.
My only concern is that, as stated in the video above, these are very low level APIs and I have no experience programming 3D ( though I am very excited to learn ). This problem should be reduced by the many 3D framework projects that will use these APIs under the hood. Those frameworks I do have some experience with and it is quite fun.
So what do you think we will see in the social media gamespace ( facebook, mySpace, vKontakte, orkut, vznet, google me, etc. )? First person shooters? Racing games? MMORPGs? The first M in MMORPG means massive and this could really mean massive. World of Warcraft has something like 13 million users and Farmville still has around 55 million monthly ACTIVE users. That is a comparison that always makes my jaw drop.
Until then I'd love to hear what you think and even what you are working on.
Testing if an object is in a set
One useful operator I've found when writing MySQL queries is the "IN" operator. The elegance of the simple statement to see if a value is equal to any item in a set is something I've alway wanted to have at my fingertip while writing much of the code I do in AS3. At some point I got tired of using something akin to as3corelib's ArrayUtils.arrayContainsValue function as I wanted to see if I could find a better solution for more readable code.
AS3's "in" operator
My first stop was AS3's "in" operator. At first it seemed like it might work and the code would look like the following:
value in [apple,banana,kiwi,orange]
Unfortunately, the previous line would only resolve to true if value was equal to 0,1,2 or 3. The in
operator only checks against the indexes of an array ( or the fields in an object ). So unfortunately it wouldn't work for my needs. It looks like I was going to have to roll my own and I wanted to see if I could create something that read like the following:
anyObject.isIn( ... args )
Actionscript is [still] a prototype language
Back in the days of AS1 and AS2 you could easily add functionality by adding to a class's prototype chain. If you wanted to add functionality to everything, all you would have to do is add to the Object
class prototype. The good news, is that this is still possible in AS3. The [not quite] bad news is that due to strong type checking you can't have a line like I wrote above without disabling strict type checking in the compiler. That's not something I'm willing to give up so I came up with something that could look like the line above but with strict type checking enabled it would look like the following:
anyObject[IS_IN]( ... args )
A little less readable than I would like but using the IS_IN
constant has a benefit of making it easy to import and use with Flex/Flash Builder. It also has the benefit of working with anything that extends objects which has some cool benefits. For instance you can write the following:
4[IS_IN]( 1, 2, 3, 4 ); // returns true
true[IS_IN]( true ); // returns true
true[IS_IN]( 1 ); // returns false
"foo"[IS_IN]( "foo", "bar" ); // returns true
If this sounds like something you might like to use feel free to download the file. I've also included my flexUnit4 test class which will show you more of how this can be used.
EDIT: There are some problems with this file as it was originally created as a proof of concept. For educational purposes I am keeping the original file up here and you can learn about the changes and why I made them at: http://ducharme.cc/flash-friday-is-in-refactored/
Caution: Example Code Ahead
Today's post veers from anything flash specific and goes to the more generic area of example code. For everything you want learn about in the world of programming there is some example code. Example code is a great way to see what book authors and blog posters are trying to explain in their posts. I'm a better programmer than a writer so I know how difficult it is to explain some of these concepts without showing code. However, example code has some issues that it is important to be aware of when you use it.
Comments aren't part of the example
Unless you are reading a book about writitng good code ( I recommend Code Complete by Steve McConnell ) the comments in the code are not there to show you good commenting practice. I could rant on and on how code should be self documenting and be able to be read like a good book but my main complaint with comments in most example code is stuff like this:
// define variable a as an integer and set it to 5 var a:int = 5
Now when you are learning about defining and setting variables this comment is important and that is why this comment is in example code. Unfortunately, I see this all too often in code I've had to debug. Code that is straight forward doesn't need to be commented. In case you don't know, comments like that in real world code scream amateur and/or I just copied this from the internet somewhere. Moving forward, you might want to make your code as straight forward as possible so you don't need to comment it.
Best Practices are rarely in example code
Recently I was reading a book on AJAX programming that was trying to show how to use a simple service written in PHP. To do this they had two input fields in a form where you entered numbers. The javascript would then send the values of those two fields to a simple PHP webservice that divided the numbers then returned the results. After that the results were parsed to show the answer on the screen. For the purpose of the book, which was to show how you could use a webservice without being overloaded with other code, this is okay. In real life, you should just divide the numbers using javascript and leave the webservice out of it.
Also, if you read books and blog posts word for word the authors know that what they are doing isn't meant for prime time so they will leave a caution warning ( possibly with a cartoony icon ) letting you know this. Please heed their advice if it is there, but since it usually isn't just realize that example code probably isn't the best way to handle the problem domain it seems to be solving.
My oh my!
This next section is about a pet peeve of mine, the use of the word "my" in example method and variable names. For instance, I sometimes run across code like the following:
var myName:String function myClickHandler( event:Event ):void{ ... }
Unlike the previous examples, I don't think the reasoning behind this convention in example code is strong enough to even use it there. The reason I don't like this convention is the readability of code that has to use it . Using the myName
variable as an example, which code appears cleaner and easier to read?
if( employee.myName == 'Jeff' )
or
if( employee.name == 'Jeff' )
I think you'll agree that the second example, without the redundant prefix is cleaner and easier to read.
The code doesn't always work
Anyone who has ever tried to copy or [GASP!] cuts and pastes example code has probably figured out that there is a high probability that it won't work. There are several possibilities for this from editors who think they know better to code that was only written in a text editor but not tested or even an errant copy and post from the author's IDE that forgot a semi-colon.
This isn't a problem in the way that the previous items are a problem with example code. Though it would probably be better if it didn't occur, its better just to know that your chances of perfectly working code are 50/50. In fact, non-working example code can be a good thing to debug. Especially when you consider a majority of your programming career ( or hobby for that matter ) will probably be taken up with debugging code that you swear should work.
What else?
While the heading for this section might make you think I'm going to discuss the overuse of if-else statements I'm really asking for your opinions on example code. Am I off base? Do you have your own issues with example code? Perhaps you want to discuss the overuse of if-else statements in example code or maybe you'd like to see more of them. Please, comment below and let me know.
[ad#Adobe Banner] If you liked this post please subscribe to my RSS feed and/or follow me on Twitter. If you only want to see my Flash Friday posts you can follow the subscribe to the Flash Friday feed. How's that for alliteration :) Until next time keep on coding.
Transitions and the Transition Manager
With Flash CS4 ( and CS3 for that matter ) comes a great utility for simple visual effects, the Transition Manager and accompanying transitions. With this tool you can use some common transitions without much complex coding on your side. The following is a list of the available transitions.
import fl.transitions.*; var transitionMgr:TransitionManager = new TransitionManager( myClip ); var params:Object = new Object(); params.type = Fade; params.direction = Transition.IN; var transition:Transition = transitionMgr.startTransition( params );
import fl.transitions.*; var params:Object = new Object(); params.type = Fade; params.direction = Transition.IN; var transition:Transition = TransitionManager.start( myClip, params );
[ad#Google Adsense]
Using Parameters
The two transition methods both take a parameters object, but you might be wondering what goes in the object. That depends on a few things and here are some options.
- The type is required - enter one of the 10 above.
- Other common properties for all transitions include
- direction - choices are Transition.IN and Transition.OUT ( default is Transition.IN )
- duration - this is measured in seconds
- easing - This is a function. I believe the default is None.none;
- You can add parameters specific to the fade type you are using( i.e. numStrips for a Blinds transition )
When does it end?
When looking at the documentation for the Transition and Transition Manager classes, there appears to be a problem. If you want to do something when the transition(s) are done there doesn't appear to be any events that tell you when this occurs. The truth is there are events that get fired, the documentation is just lacking. The events that get fired are of type flash.event.Event and there are no constants to give you any auto completion help.
For the transitions the following events may be fired:
- "transitionInDone"
- "transitionOutDone"
- "transitionProgress"
The TransitionManager fires the following 2 events
- "allTransitionsInDone"
- "allTransitionsOutDone"
Example
With all the above in mind I thought I would show each of the different transitions and the events that fire. Each transition uses all of its defaults, but you do get to choose the direction so you can see the different complete events :)
One Last Thing
The Transition classes unfortunately are only coded to work with MovieClip instances. For many people who don't code in MovieClips you may have to find a different solution but for most users of Flash CS4+ this shouldn't be a problem. [ad#Adobe Banner] If you liked this post please subscribe to my RSS feed and/or follow me on Twitter. If you only want to see my Flash Friday posts you can follow the subscribe to the Flash Friday feed. How's that for alliteration :) Until next time keep on coding.
The Year Ahead For Flash
What's new for flash in 2010? There is lots in the pipeline. Let's take a look at some of the highlights.
2010 is looking to be an exciting year in the world of Flash. For the first Flash Friday post of the New Year I thought I would go over some of the big new things I am looking forward to in 2010.
Flash Player 10.1
Flash truly goes mobile this year and this is made possible by many of the changes in flash player 10.1. Many performance optimizations have been made to the player to allow better performance and this will help out, not only mobile, but all forms of the flash player. Mobile devices also require new interface methodologies and thus flash player 10.1 will be able to handle multitouch events and gestures. This is huge in mobile but will also be making a difference on the desktop with another thing I am looking forward to AIR 2.0.
AIR 2.0
Flash Player 10.1 is at the heart of the newest version of the AIR runtime. Along with some of the other benefits of Flash Player 10.1 such as gesture events there are some AIR only improvements. As a former audio professional the access to the Microphone sound is exciting. Other stuff I'm looking forward to are global error handling, detection of USB devices, more sockets and file promises.
Flash Builder 4
Flex builder is being rebranded as Flash Builder and there are lots of changes. I've been a fan of Degrafa for a while so the new graphic changes are something I'm looking forward to. The new spark architecture will take some getting used to but the design flexibility will be nice. Though I've got an e-article available on Amazon that will be mostly worthless, the better integration between Flash Builder and Flash CS5 will make my life much easier.
Flash CS5
The big thing with this new version of Flash CS5 is IPhone application development. Unfortunately, at this time it looks like that's the closest that the I-platform is coming to having flash in 2010 unless something major changes. Everyone else having flash in the mobile market may be the catalyst that makes this happen. Speaking of a catalyst...
Flash Catalyst
I've been looking forward to this for a long time. Better integration between a design tools and Flash Builder. I've loved using Flex Builder since Flex 2 and Flash Catalyst will ( hopefully ) make a dramatic change in our office workflow. Also, this could be a boon for user experience architecting if all is done correct.
So what else is coming? What are you looking forward to? I've only touched on what Adobe has announced here but maybe you've heard a rumor. [ad#Adobe Banner] If you liked this post please subscribe to my RSS feed and/or follow me on Twitter. If you only want to see my Flash Friday posts you can follow the subscribe to the Flash Friday feed. How's that for alliteration :) Until next time keep on coding.
wmode:gpu not a magic bullet
At my current work, Provis Media Group, we do a lot of video for the web. We've had a lot of success with larger format video than is usually delivered via the internet. When Flash Player™ 9.0.115 came out allowing fullscreen h.264 video delivery things really took off. Quality went way up and we were able to deliver 720p+ content over the internet. In full screen it looked great. However, when we shrunk a video smaller than its true size some artifacting would occur. Really, it wasn't that terrible but we pride ourselves on the quality of video we deliver, especially since most of it is done in house. When flash player 10 came out we noticed 2 new wmodes, direct and gpu. Both were suppose to affect drawing performance on the screen and we thought gpu mode should improve the quality of our videos. In order to be sure we had to test it and compare it to the default mode that we almost always use.
Test after test proved that there really wasn't any noticeable difference. In fact, wmode=gpu didn't provide any noticeable playback difference but it did affect the player. [ad#Adobe Banner] The more we read, the more it sounded like wmode=gpu really wouldn't do much for most people until Flash Player™ 10.1 ( currently in beta 2 version on Adobe labs ). Installing Flash Player 10.1 did improve performance on the CPU ( which is awesome ) but their still wasn't a difference from the default.
In the end the best thing to do with our video was to turn smoothing on. This actually made a dramatic improvement. In Flash Player 10.1 you get enough of a performance increase to make this work on even slower computers than before.
So wmode=gpu still may not be a magic bullet unless you control the playback platform but turning on smoothing gives you good performance if you are having artifacting when your videos get resized. You still need to be concerned about cpu performance ( for now ) but flash player 10.1 will really improve that.
If you have had different results or even the same, I'd love to hear your experiences. If you celebrate Christmas today then Merry Christmas and to everyone Seasons' Greetings and Happy Holidays.
Decreasing load times with RSLs
Recently, Adobe released version 3.5 of the Flex SDK. I updated a project I was currently working on from 3.3 to 3.5 and I had to reset up my runtime shared library (RSL) for the project. This got me thinking that many people don't know how to properly use RSLs. The world of flex development is better if we all use the the SDK RSLs so that is the topic of today's post
[ad#Adobe Banner]Every Flex application that you create uses the same class files. Some of these are your class files, some are other libraries you have included and then of course you have the files that make up the Flex framework itself. One of the constant complaints I hear about Flex apps ( and flash in general ) is that it takes too long to load. One reason for the long load times is that every Flex application needs to be sure it has all the classes it needs, so all the necessary classes get compiled into the SWF. So, even if the same classes are used in most of the applications you create you are reloading that data again with every new application that gets loaded. Not only is this reloading of data bad for your application but much of what gets reloaded is the Flex framework itself. The fact that it gets reloaded with every Flex application out there means it is adding to bandwidth use on the internet and thus bad for the image of Flex and Flash. Before you give up and start exclusively building AJAX applications, I'd like to introduce you to runtime shared libraries (RSLs).
RSLs were introduced in Flex to allow common libraries to be extracted from Flex application SWF files and put into their own files. That way the Flex apps that use classes from the library(ies) would be smaller and the classes would only need to be loaded once for all the SWF files that need them. Originally there were only two types of RSLs, signed and unsigned. Basically this is still the case but unsigned RSLs are now split into standard and cross-domain varieties while signed RSLs are now referred to as Framework RSLs.
The great thing about the signed, Framework RSLs ( and to a lesser extent cross-domain RSLs if the location used is the same ) is that once someone has loaded the RSL of that Flex SDK on their system, they shouldn't have to reload it for any other app that requires that RSL. In other words, if someone has used another app that required the same Flex SDK (3.2, 3.3, 3.5, etc ) RSL as your app requires then your application will benefit with faster load times ( and vice versa ).
For today's post we are going to focus only on using RSLs. I will save the lesson on creating them for another post if there is interest. Because of this fact I will explain how to use the framework RSLs specifically, but the same technique can be used with standard and cross-domain RSLs.
Using the framework RSLs is actually quite easy. It is even easy enough to take existing live apps and set them up to use RSLs in an effort to decrease load. I made one of my clients, extremely happy by doing this one little task.
In the Flex Build Path screen of project properties window select the Library Path tab ( you can also do this when initially setting up a project ). At the top of you should see a ComboBox labeled Framework Linkage: and you are given the choice of Merged into code (the default) or Runtime shared library (RSL). Select Runtime shared library (RSL). If you are going to have your RSL files in the same directory as your SWF, then that is all you need to do, as your RSL files will be in your bin-debug/bin-release folder along with your application SWF. For the Flex 3.5 SDK these are framework_3.5.0.12683.swz and framework_3.5.0.12683.swf. The SWF is just a backup for the SWZ.
[ad#Google Adsense] If, however, you want to put your RSL into a different location on your server, or on a different server altogether, you'll need to take a couple extra steps to let your application know where to look. The framework RSL files will still show up in your bin-debug and bin-release folders next to your application SWF but it will look for them in a different location. To make these changes you'll need to go to the tree view labeled Build path libraries: and open the node for your flex SDK ( in my picture it says Flex 3.5 ) and then open the node that says framework.swc. Select the node that says RSL URL: and click the Edit... button on the right that probably just became enabled. The only thing you want to edit here are the deployment paths.
When editing the deployment paths for BOTH the SWZ and SWF files, you have the ability to edit 3 things:
- An input field labeled - Deployment Path/URL:
- A checkbox labeled - Copy library to deployment path
- Another input field labeled - Policy file URL:
The deployment path input field is the path to your SWZ or SWF file. Relative paths are acceptable and I recommend using them. The copy library checkbox is used to tell Flex Builder whether or not to include the SWZ or SWC file in your bin-debug/bin-release folders. I like to uncheck this once I already have a copy of the SWZ and SWC available somewhere else because I'm not a big fan of having multiple copies of the exact same file on my computer. The policy file field is used for RSLs served from different domains. It is the path to the appropriate cross-domain policy file. As such it needs to be an absolute path. Cross-domain policy files are out of the scope of this document but more info can be found at: http://livedocs.adobe.com/flex/3/html/security2_04.html#139879.
Now that you have set up your project just upload the RSL file(s) to the appropriate location and everything should be ready to go. You probably noticed quite a difference in file size and on subsequent loads should see an improvement in loading time. However there is one problem that is common with RSLs.
Usually you will get an RSL error if the RSL files aren't where your application SWF is expecting them to be. An easy enough problem to fix. The problem arises in that you won't be able to recreate this error if you already have the files in your cache. Another hiccup is that, while standard and cross-domain RSLs are stored in your browser cache, signed framework RSLs are stored in the much lesser known flash cache. The flash cache is the location shared objects are stored in. It can be managed via the Adobe Flash Player™ Settings Manager's Global Storage Settings tab ( available at: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager03.html ). Just uncheck the store common Flash components to reduce download times checkbox while testing to make sure you load the framework RSL every time instead of pulling them from your cache.
I highly recommend using the runtime shared library for the Flex framework on all your Flex projects. This will speed up the load time of all Flex applications online that are set up to use them and that is good for all of us. The other reason is that there are some drawbacks to using RSLs and the framework RSLs don't really suffer from any of them. In fact from the looks of beta 1 and beta 2 of Flash Builder 4, the framework runtime shared libraries are going to be set by default and they'll be served up by Adobe's own servers. I hope this remains true upon release as it will greatly help Flex apps and their image in the developer community. [ad#Adobe Banner] If you liked this post please subscribe to my RSS feed and/or follow me on Twitter. If you only want to see my Flash Friday posts you can follow the subscribe to the Flash Friday feed. How's that for alliteration :) Until next time keep on coding.
Embedding Fonts in Flex Builder Using the Flash IDE
[ad#Adobe Banner] Flex is great for building rich internet applications quickly. Building an application quickly is nice, but to give your application that truly professional touch you need to customize the look and feel of your app. In order to fully customize the look and the feel you will need to use a font that's different than the default serif font that is used everywhere.
The flash player affords you the opportunity to embed many non standard fonts into your app, something that sets it apart from AJAX applications that need to rely on web safe fonts. In the flash IDE this is as easy as setting the font in the properties panel and selecting which character from that font which you want to embed. In a Flex app, things get a little trickier - especially if you want to use a non True Type font, which is the only type it can import natively. However, if you have the Flash IDE you can use its simplicity to get any font you can use in Flash into your Flex app.
The process is broken up into two steps.
- Create a SWF with the font(s) you need embedded in it
- Add Style (CSS) info to your Flex project that imports the font into your Flex project
Step one starts with the simplest of FLA files and can be created with earlier versions of the Flash IDE (so you can use Flash 8 or MX2004 if that's all you have). I recommend using a separate FLA for each font you want to embed, that way it is easier to catalog, store and reuse in other projects. Create 4 dynamic text fields. Each text field is for the different versions of the font so you should have:
- normal
- italic
- bold
- bold italic
You need to make sure you set up all 4 text fields to embed all the glyphs from the font you will need. For most western languages Numerals, Punctuation and Basic Latin should cover all the glyphs you will need. Once again, make sure to set up the character embedding for all 4 text fields. If you notice certain parts of your flex document using the default font you may not have set up character embedding. You can of course leave out any of the 4 ( ie italic and italic bold ) that you aren't going to use but if you are going to reuse the SWF I would do all 4.
Once you are done setting the character embedding for all 4 text fields, publish the file to a SWF. [ad#Google Adsense] The second step of this process is to add Style to your Flex project that imports the font into the project. That's as simple as adding an @font-face entry to your CSS file or <mx:Style> block. At first you simply give it the path to your font SWF and the name of the font ( ie Futura Book, Calibri ).
@font-face
{
src:url( "path/to/yourFont.swf" );
fontFamily:"Exact Name of Font"
}
You also need to add an @font-face entry for each version of the font you want to use. So if you also wanted to use the bold version you would add the following:
@font-face
{
src: url( "path/to/yourFont.swf");
fontWeight:"bold";
fontFamily:"Exact Name of Font";
}
After you are done adding the appropriate @font-face entries you can style any component you need to or you can style the entire application with your font.
Application
{
fontFamily:"Exact Name of Font";
}
There are a couple other ways to embed fonts, and if you don't have a version of the flash IDE those are the only way to go. If there is enough interest I can cover those in comments or another post. However this is by far the simplest, it allows you the ability to embed non True Type fonts and you can reuse a font more quickly in the future. [ad#Adobe Banner] If you liked this post please subscribe to my RSS feed and/or follow me on Twitter. If you only want to see my Flash Friday posts you can follow the subscribe to the Flash Friday feed. How's that for alliteration :) Until next time keep on coding.