Tip of the Day – Getting a SWF’s background color

Recently at ZaaLabs, I’ve been working on a really cool tooling platform called Eden. One of the features that Eden has is a Screen Capture plugin. Eden can send a request to a remote SWF to return a bitmap of the stage.

For example, here is Eden pulling a screen capture from HanClinto’s Platformer Starter Kit.

Really cool! However, I quickly ran into an issue when I tried to take a screen capture of a more basic game.

On the right is the game running in Flash, and on the left is the screen capture.

As you can see, my screen capture doesn’t include the green background. So what happened?

Well it turns out the background color of a SWF isn’t actually part of the stage. The background color that you set using the SWF Metadata tag, or set in Flash Professional is drawn directly by Flash Player.

package
{	
	import flash.display.Sprite;
 
	[SWF(backgroundColor="0x00FF00")] // <--- How can I get this programmatically?
	public class SwfBackgroundExample extends Sprite
	{
		public function SwfBackgroundExample()
		{
		}
	}
}

So I had a dilemma… how could I access the backgroundColor of the SWF? I scoured the API docs, I asked the Twitter-sphere, but no luck. All I learned was that the backgroundColor was hard coded into the bytes of the SWF. So I decided that’s where I needed to look for it.

SwfData to the rescue.

I read up on the Adobe SWF specification, and consulted with my good friend James Ward. He pointed me in the direction of loaderInfo.bytes, which gives us access to the bytes of the currently running SWF.

After a few hours, I had a fun little class I like to call SwfData, which parsed the background color out of the currently running SWF’s bytes… as well as some other fun things. Here’s how you use it:

package
{
	import com.zaalabs.utils.SwfData;
 
	import flash.display.Sprite;
 
	[SWF(backgroundColor="0x969696")]
	public class SwfDataExample extends Sprite
	{
		public function SwfDataExample()
		{
			var data:SwfData = new SwfData(loaderInfo.bytes);
 
			trace("version \t"+data.version);
			trace("frameRate \t"+data.frameRate);
			trace("frameCount \t"+data.frameCount);
			trace("fileLength \t"+data.fileLength);
			trace("bgColor \t0x"+data.backgroundColor.toString(16));
		}
	}
}

Using SwfData, I could now use the background color as the fill color of my BitmapData class.

Get It Here

SwfData is MIT licensed under ZaaUtils (do with it what you will). It is available on GitHub

Questions, comments, complaints are all welcome below.

== UPDATE ==

So I just found out that Claus Wahlers has an awesome, more feature complete version of an AS3 SWF parser. It’s also available on GitHub. I’m still going to keep SwfData up since it’s much more specific to getting the background color of the swf. If you need more features, use as3swf by Claus, it’s very well done.

Related Posts

Comments Closed