Loading Fonts at Runtime

Tue Jan 5 09:53:51 2010

One of the painstaking things about creating swf files is embedding large font files which often end up bloating your flash movies and causing long wait times for your users. But what if I told you that there is a way to load fonts at runtime? Well, there is and it just so happens that I have prepared an example to guide you through it, allowing you the peace of mind that you can easily import the fonts you need when you need them and create subsets of them when every character in a font set is not necessary, and thus giving you a lot of power indeed.

Creating a SWF Contained Font

First off, you need to create a swf file containing the font that you wish to load into your movies. The big advantage to this is that you can have a library of preprepared swf files containing all your favourite fonts to load when and where you want. To understand how this is done, take a look at the following code.

package
{	
   import flash.display.Sprite;
   import flash.text.Font;
	
   public class FontEmbed extends Sprite{
      [Embed(systemFont='OCR A Std', fontName="OCR", 
      mimeType="application/x-font", unicodeRange="U+0041-U+005A")]

      public var ocr:Class;

      public function FontEmbed(){
         Font.registerFont(ocr);
      }
   }
}

On lines 7-8, we simply embed whatever font we want to be contained inside the swf file that is to be output on compilation of this class. In this example, I have chosen the font OCR A Std because it is a rather unusual font and will stand out against default fonts when testing to see if the font was actually embedded correctly. To embed your own font, simply change the systemFont string to the name of a font on your system if you don't have OCR A Std, which is highly likely if you are not on a Machintosh. The fontName can be any name you choose to remember this font by. This is important because we will be using this name to load in the font later. In my example, I have chosen the name "OCR" for simplicity. The mimeType is not something to worry about as it simply tells the Flex SDK what type of file to expect. Finally, the real power comes with the use of unicodeRange, which allows you to determine a range of characters you wish to embed. In this case, I have chosen the range U+0041-U+005A which is simply Unicode for A-Z.

There is a great little list of Unicode values to be found here at Wikipedia. Also, if you are running a mac, you could simply open a program such as TextEdit and go to Edit > Special Characters and roll over the characters to display their Unicode values. I'm sure Windows has something similar but don't quote me on that.

Continuing on, any font embedded must be datatyped to a Class, which is what the code on line 10 does. Finally, inside the constructor function on line 13, we register the font using Font.registerFont. Don't forget that to access any method of the Font class, you must import flash.text.Font (see line 4).

Once all that is done, simply compile the class to create the swf file containing your prefered font. As nothing has been added to the display list, nothing will be visible if you choose to view the swf file at this point.

Loading the Contained Font

Loading fonts is pretty simple. Take a look at the following code.

package
{	
   import flash.display.*;
   import flash.events.Event;
   import flash.text.TextField;
   import flash.text.TextFormat;
   import flash.text.TextFieldAutoSize;
   import flash.net.URLRequest;
	
   public class FontLoading extends MovieClip{
      private var ldr:Loader = new Loader();
      private var txt:TextField = new TextField();

      public function FontLoading()
      {
         ldr.contentLoaderInfo.addEventListener(Event.INIT, loaded)	
         ldr.load(new URLRequest("FontEmbed.swf"));
      }
		
      private function loaded(event:Event):void{
	 addChild(txt);
	 txt.autoSize = TextFieldAutoSize.LEFT;
	 txt.embedFonts = true;
	 txt.defaultTextFormat = new TextFormat("OCR", 22, 0x333333);
	 txt.text = "THIS FONT WAS LOADED AT RUNTIME";
      }

   }
}

On line 11 I have instantiated a Loader called "ldr", which will be used to load the font. The TextField on line 12 will only be used to display the results and is not necessary to load the font itself. On line 16, we add an EventListener to listen for the INIT event which basically means it will be waiting for the load to begin. Once it does, it will call the loaded function on line 20. The loaded function will add the TextField txt to the display list and auto-size it to fit the text on line 22. On line 23, we tell flash to use Embed fonts if it finds any (it should find our font) using txt.embedFonts = true. On line 24, we set the defaultTextFormat font on the TextField "txt" to "OCR". This is the name of the font we set when we compiled the swf containing our font, and this is how the Flex SDK will know which font we would like to use. On the same line, we set the font-size to 22 and the colour to a dark grey (0x333333). Finally on line 25, we give the TextField some text. All that is left is to compile the class and marvel at the wonder of loading fonts at runtime... a truly beautiful thing.

Download Runtime Font Files Here

Traverse Class - Useful Utility

Tue Dec 29 05:49:39 2009

How often have you had to make a photo gallery or something else that requires an index to be traversed? I know that I have come across this a lot and quite honestly I am tired I rewriting the same code over and over again. Thus, I've finally forced myself to write a class that will traverse an index and easily allow the assignment of objects that control the incrementation/decremental of said index... and I just thought I would share it with whoever is interested.

It's actually more of a helper/convenience class than anything. But I know I will personally be using it a lot in the future. The example below shows two arrows linked to an index displayed in a textfield. Click the arrows to see what I mean.

What It Does

Get Adobe Flash player

Code Example

import Traverser;
Traverser.init(MovieClip, "inc/dec", limit, callback);

How to Use This Class

Simply import the class as in the code example and then initiate the class using the Traverser.init() call. This class requires no instantiation. The first parameter labelled MovieClip should received the MovieClip that is to act as a button, like the two arrows in the swf example above.

The second parameter is a String where "inc" makes the MovieClip passed in the first parameter increment the index of the Traverser class, and as you would imagine, "dec" makes the MovieClip passed decrement the index.

The limit parameter determines the maximum limit the index will increment to before the index returns to zero. The limit of swf example is 5, and therefore the textfield will never display a number higher than 5.

Finally, the callback parameter will allow a call to a separate function once the index has been incremented or decremented. For those who are interested, in a way, the callback functionality is like a call to dispatchEvent(new Event()) calling a public static const, although all it really does is calls the function passed from inside the Traverser class. I thought this would work better than the alternative as I am using the Singleton approach and this is because I didn't feel the need to instantiate for as little as an index number, which is essentially what we are dealing with. Anyway, in the swf example above, I am using the callback function to update the TextField and give it a TextFormat. Without the callback to update the TextField, the TextField would not display any changes to the index.

Also, the index is contained inside a public variable and so can be access via Traverser.index to pull the current value. Again I didn't feel the need for getters and setters in this case, but if that's what you would prefer, feel free to update the code.

Download the files from the link below for a closer look at an example and for the code behind the arrow buttons.

Download the Traverse Class Here

Happy traversing!

Shorthand 'if else' Statement (ternary)

Sat Dec 26 04:15:23 2009

There's a lot to be learnt from simple reviewing the basics of programming on occasion, as my recent experiences have shown. Today, I would like to share a little shorthand 'conditional statement' with you that I've picked up along the way, which may help from time to time in your own coding.

As you may already know, the most commonly seen conditional statement syntax in ActionScript 3.0 is as follows:

Example 1

var sayHello:Boolean = false;

if(sayHello == true){
   trace("hello");
}else if(sayHello == false){
   trace("goodbye");
} 

//traces("goodbye");

This can be shorted to a single line in most, if not all programming languages to something like the following:

(checkstatement)? doSomething() : doSomethingElse();

So if you wanted to do the same thing as the if statement in Example 1 above, you might do this:

var sayHello:Boolean = false;

(sayHello)? trace("hello") : trace("goodbye"); //traces goodbye

sayHello = true;

(sayHello)? trace("hello") : trace("goodbye"); //traces hello		

In actual fact, I have to confess that this is something that I have learnt from my endeavours into the world of PHP, but its use is far wider and I'm sure that it will help make your coding a little bit tidier and easier to read. If anyone discovers any limitations to either way, I would love to hear about them.

Compile AS files with Flex SDK

Thu Dec 17 00:35:34 2009

At the time I began learning ActionScript in Flash, which is probably where most of us start, Flex was not something I even considered. At that time, the timeline looked all too comfortable and compiling from classes alone simply looked like far too much hard work. However, all that has changed now and as I wrote in one of my earlier posts, with the use of SVG and FXG(Flex 4),the albeit wonderful drawing tools of Flash are no longer necessary. So with that said, there are no excuses not to try it out.

Before you attempt anything though, get over to Adobe Open Source and download yourself the Flex SDK and save it somewhere you can get your hands on it easily. I'm currently using Flex 4 (Gumbo), which is at the beta stage at the time of writing this post. Those who like stability should grab the latest Flex 3 version. Either will suffice for our purposes.

Once your download has finished and has been unzipped, you should have a folder called flex_sdk_3 or flex_sdk_4, depending on which version you downloaded. Inside this folder, you should find a folder called 'bin' inside of which you will find a file called 'fcsh'. The file 'fcsh' is the Flex Compiler Shell and will be used to compile our classes.

The other thing you are going to need is a file to compile. For your convenience, here is some code that will get you a little 'Hello World' project going. Just save it as Main.as

package
{
   import flash.display.*;
   import flash.text.*;
	
   public class Main extends MovieClip
   {
      	private var txt:TextField = new TextField();
	private var txtFormat: TextFormat = new TextFormat( "Helvetica", 22, 0x333333);
		
      	public function Main()
      	{
		addChild(txt);
		txt.selectable = false;	
		txt.autoSize = TextFieldAutoSize.LEFT;
		txt.text = "Hello World";
		txt.setTextFormat( txtFormat );
		txt.x = stage.stageWidth/2 - txt.width/2;
		txt.y = stage.stageHeight/2 - txt.height/2;
      }
   }
}
Compiling using Flex Compiler Shell (fcsh) in OSX

Compiling using Terminal is very easy. First open it up. If you have never used Terminal before, you'll probably find it inside the Utilities folder inside your Applications folder. Once Terminal is open, we need to use it to open up the Flex Compiler Shell. There are three ways to do this on Mac. You could type the location of the fcsh file into Terminal and press Enter. You could drag and drop the fcsh file into the Terminal window and press Enter, or you could just double click the fcsh file.

Compiling using Flex Compiler Shell (fcsh) in Windows

Compiling in Windows is virtually the same process to that of a Mac. The only real difference is that you use Command Prompt instead of Terminal and you open the fcsh jar launcher instead of the fcsh unix executable file.

Whichever way of you choose on whatever OS you use, you should be faced with a Terminal/Command Prompt window that displays the following on it's last line.

(fcsh)

If for some reason, you cannot open the fcsh or are not greeted with (fcsh) in Terminal, go get another build. Chances are that another build will work out for you.

If you do see the (fcsh) message, compiling from here is easy. Type the following code and press Enter.

mxmlc -o="The location you want to output to" -file-specs="The localation of you class"

If your Main.as file is on your desktop on OSX and you want to save the swf to the same location, the line above will look like this.

mxmlc -o=/Users/YourName/Desktop/Main.swf -file-specs=/Users/YourName/Desktop/Main.as

Instead of typing the full location, something I sometimes do is type mxmlc -o= and the drag the file I want to compile into the Terminal windows and then change the '.as' to '.swf' and then continue typing, again dragging the class file into the Terminal window after the -file-specs part.

Provided everything was fine with your class, you should now see a .swf file in the output location you entered. If you open that up, you should be greeted with the words "Hello World". Congratulations! It's not really that hard and the advantage to compiling using fcsh as opposed to other methods available is that it shaves a lot of time of the each compile. As long as you don't close the Terminal window, what you compiled previously will still be in the compiler memory and it will simply recompile any changes to your files rather than recompiling the whole thing.

In my opinion, this is a great free alternative to any of the paid software out there. Anyone who hasn't should definitely check this out. For choice of good editors, FlashDevelop (free) seems to be most peoples choice of free editors on Windows, and I personally am a big TextMate (paid) fan and thoroughly recommend it for all types of coding on OSX. As a side note, compiling can be done from inside either of these editors which makes life a lot easier too.

Magic Mouse is a Hit with Me

Mon Dec 14 01:15:30 2009

I wrote a post a few weeks back about the new Apple Magic Mouse and said that if I ever got one of my own, I would write about my experiences. Well, it was my birthday recently and my dear ol' mom actually forked out for one for me. My first impression when I got it was how well presented it was, which I suppose is nothing new where Apple is concerned. The design of the mouse is very sleek and it doesn't feel as round or as bulky as it's predecessor - the Mighty Mouse.

The scroll functionality works flawlessly but with an added feature that I was unaware of until I got my hands on it. The mouse can actually detect how fast your finger scrolls across it's shiny surface and it will scroll accordingly, which is great when you want to get to the end of a long web page really fast in one quick swipe of your finger. The way it scroll kind of reminded me of how the iPhone scrolls as that also detects the speed of your scroll.

At the bottom of the mouse are two black extrusions kind of like skiis which raise the mouse a good 3mm from whatever surface you are using it on. The Might Mouse, however, was rather low and often allowed dirt or pencil rubbing to get trapped underneath (Yes, I know I should clean my desk more often) hindering the movement of the mouse.

The two silly buttons at either side of the Mighty Mouse, which in my opinion did more harm than good as my clumsy fingers would often press them by mistake, have been removed too. In the end, I chose to turn them off with the Mighty Mouse, but with the Magic Mouse, that's not a problem anymore.

One thing that I have found that I miss is the ability to press the very center of the mouse (scroll ball on Mighty Mouse) and have the daskboard widgets show. With the new Magic Mouse, there is only a left and a right click, so I guess Magic Mouse users will have to press F12 to bring the daskboard up for now.

Anyway, in conclusion, if you're thinking of buying one, I would strongly recommend it. It's a very simple mouse, and although I'm not sure it quite justifies the price, it will certainly be one of the better mice you've had for your apple computer.

Most recent posts

  1. Convert Font Suitcase to TTF in 3 Easy Steps
  2. Rain or Shine - Weather Forecast Available Now!
  3. Getting around Apple's silly rules for iOS 10
  4. Localising App Names for iOS and Android
  5. Today - Powerful To-Do App Now Available on iOS & Android

Search site:

Apps by Ubacoda.com

Click the app icons to see more info


Archives

Categories