# Quick Tip: Guide to Creating and Using SWCs

##### Tutorial Details
• Program: Flash Builder
• Difficulty: Beginner

As ActionScript 3 becomes a more popular language and Flash Player’s features become more advanced and accessible, it’s important to build a common workflow within your company so that projects can become more agile and, more importantly, get delivered on time. One major issues with ActionScript 2 was bridging the gap between the designer and developer. This often left developers dealing with FLAs which contained hundreds of badly named library items and no one liked that.

With the advances of ActionScript 3 and the ability to code away from the timeline, SWCs have become commonly used items on large projects, but there are still many people out there who don’t know what they are or how to create/use them.

## What Are SWCs?

Let’s start by seeing what SWCs actually are. A SWC [ShockWave Component acronym say:Sw~iCK] :) is simply a zipped up package of files generated by the Flash IDE. They contain visual assets (such as MovieClips, Buttons, Graphics and Fonts) as well as code. SWCs have been around since Flash MX 2004, but have only really taken off since ActionScript 3 came around because before, like I said, you could just keep everything in the FLA.

In this tutorial, I’ll be showing you how you can embed and use visual assets, fonts and ActionScript code.

## Why Use SWCs?

There’s a simple and solid argument for using SWCs: it separates the design from the development. Flash has the ability to influence the design of programmed visual items through ‘CSS’ like stylesheets (much like with Flex) but most of the time designers (not all of them) are put off by anything to do with code, including simple CSS. Another point is that designers design. They are usually given mock write frames from which they then create user interfaces in programs such as Photoshop and Illustrator. If they then had to code the interface, then creating the mock ups in Photoshop may’ve been just a waste of time. Furthermore it can take a lot of time and effort to code interfaces that can be easily created in visual IDEs such as Photoshop and Illustrator.

Back to my main point, the SWC allows the designers to design the interface, cut it up and then pass a SWC to the developer who ties it all together, this creates a simple workflow without people treading on others’ toes in order to achieve the correct design.

## Where Would You Use SWCs?

Let’s say tomorrow you’re briefed on a new project whereby you’ll be working with a design team. It’s going to be the design team’s responsibility to build the interface including creating all the little things such as button hover states, loader animations, rounded corners and icons. It’s the development team’s responsibility to then build the project and bind in all the UI elements as well. The design time would create all the elements they need, put them into a SWC and then pass that file to the development team. The development team can then code in the UI elements without having to worry about importing fonts, playing with stylesheets or sitting with the designer and programming the interface.

## What’s the Difference Between SWCs and FXGs?

As Mario Santos’s great article points out, Adobe have recently released Flash Catalyst, an IDE which allows you to import PSD or AI files and convert them into XML based vector objects, FXGs. This is definitly a step in the right direction, but it’s something only implemented in Flash Player 10, of which there’s only about a 75% penetration rate. This means that when working on live projects we need to use Flash Player 9, so until more people adopt Flash Player 10, SWCs are a good way to go about it.

## Step 1: Creating Your First SWC

Enough talk, let’s create a SWC. I’m going to create a few graphics in Photoshop and Illustrator and bring them into the Flash IDE where I’m going to set them up for ActionScript coding through using SWCs. I’m also going to talk about a concept called "scale 9 grid" slicing, so fire up your favourite image editor and create a new file:

Let’s just take some default custom shapes Adobe provides and stick them on the art board:

Then so that we don’t just have solid black bitmaps, let’s add some colour to them:

OK, so we have some pretty stars, we now want to take them and put them into our Flash IDE.

## Step 2: Importing the Assets

Fire up the Flash IDE and create a new ActionScript 3 file:

Now, if you’re a veteran of the Flash IDE, you’ll remember that you’ve been able to import PSD files since CS3, they introduced a really nice interface when it came to importing PSDs that would go through your layers rather than importing one big bitmap. So go to File > Import > Import to Library, navigate to your PSD and click Import to Library. You’ll get an window pop up similar to this:

In my case, I’ll leave everything ticked apart from the background as it’s just a white background. Now we have our PSD layers as items within our library, we can begin getting them ready for the developers. Take one of the stars out of the library and just drop it onto the stage, like so:

We then take the star and convert it to a MovieClip. When the window appears, name it "BlueStarAsset", tick "Export for ActionScript". You’ll see the two input boxes below become editable. You don’t need to touch them, but they allow us to specify what class this asset will be called and what type of class it will extend, we’ll stick with "MovieClip":

Now we have an asset in our library which we’re able to export to ActionScript. Before we go on, let’s try this out. Firstly go to File > Publish Settings. Click on the "Flash" tab, select "Player" version 9 and tick "Export SWC":

Hit "Ok". Now we’re ready to export our SWC. Debug the FLA by hitting CTRL/CMD + Return and you’ll see a SWF and a SWC file. Whey! You’ve created a SWC, now let’s just quickly use it. Fire up your favourite coding IDE and create a new ActionScript 3 project. Configure the compiler settings to include the SWC you’ve just created in the build path. Create a new base ActionScript 3 file called "App.as" and use the following code:

	    package
{
import flash.display.MovieClip;
import flash.display.Sprite;

[SWF( width='600', height='400', frameRate='30', backgroundColor='#FFFFFF' )]

public class App extends Sprite
{
public function App()
{
var star:MovieClip = new BlueStarAsset();

}
}
}


You’ll see something like this:

So that’s our star asset.

## Step 3: Resizing Assets

I’ll just quickly talk about a concept called "scale 9 grid". This is simply a method which allows us to slice up a visual asset so when it comes to resizing it, things like rounded corners can stay in proportion. For example, if we had a rounded rectangle like this, if we then changed it’s width, you see that the rounded corners are not longer in proportion:

To overcome this, we use the scale 9 grid slicing method to set a rectangle on top of our asset that will be resized, so everything outside the rectangle stays in proportion, for example:

The red rectangle in the middle is what will scale, but the stuff out side won’t. We create a 9 way grid, the top row has 3, middle has 3 and bottom has 3. This is how we do it in a practical sense, go back to the Flash IDE and just draw a simple rounded rectangle. Create a new movieclip from it and make sure that you tick the "export for ActionScript" box (I’ve called mine "SimpleRoundedRect") and hopefully you’ll have something similar to this:

Now we’re going to take this newly created asset, re-export the SWC (by debugging the movie) and go back to our ActionScript 3 IDE where we’ll update our class like so:

	    package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.geom.Rectangle;

[SWF( width='600', height='400', frameRate='30', backgroundColor='#FFFFFF' )]

public class App extends Sprite
{
public function App()
{
var rect:MovieClip = new SimpleRoundedRect();

rect.scale9Grid = new Rectangle( 10, 10, rect.width - 20, rect.height - 20 );
rect.width = stage.stageWidth;

}
}
}


We’re simply adding our rectangle to the stage, but before that we’re drawing a rectangle that’s x: 10, y: 10 and is 20 pixels less in width and height to our rounded rectangle. This will be defining the middle rectangle for our scale slicing. You’ll now see the rectangle go the full width of the stage without the corners going out of proportion. Just to see the difference, comment out line 15 (it starts with "rect.scale9Grid") and see how the corners are now stretched.

I know exactly what you’re thinking "if the designer is meant to do all the asset work, then why does the developer have to set the rectangle for the slicing?" Well the developer doesn’t have to, as the designer can! Right-click on the asset in the library and select properties. Then tick the box labelled "Enable guides for 9-slice scaling", and you’ll see this:

Now the designer can reposition those guides so that the developer doesn’t have to worry about creating a rectangle for the scale 9 grid. If you leave line 15 commented out and re-export this SWC, you’ll see that the corners are now once again proportionate. Simple eh?

## What About Code?

SWCs can hold more than just visual assets, whether they are flat graphics or timeline/scripted animations. They can also hold full code libraries. SWCs are a very good way to distribute your code. It’s quite a chore, but not impossible to decode SWCs. However, it does mean that you can post a SWC rather than having to worry about lots of files and directories. They’re also easier for the user. I, for example, have a folder where I dump any ActionScript code libraries that I use or create, but then I have a separate folder for useful SWCs I’ve come to use. I find it easier selecting a SWC and binding it to the project rather than including the whole of my shared scripts folder – and it’s faster too!

## Step 1: Create a New Flex Library Project

In order to create code based SWCs, I’m using Flash Builder – you can download the beta from Adobe. Within Flash Builder you’ll need to create a new "Flex Library Project" like so:

Give it a name and make sure you select the Flex 3.4 compiler:

Click next and then tick the box next to "src", this is where we’ll put our classes:

Now we can start writing code for our library, so create a new ActionScript class, call it "Test" and set the package name to "com.flashtuts.swc" and put the following code in there:

	    package com.flashtuts.swc
{
import flash.display.Sprite;

public class Test extends Sprite
{
public function Test()
{
init();
}

private function init():void
{
var sprite:Sprite = new Sprite();

sprite.graphics.beginFill( 0xFF0000 );
sprite.graphics.drawRoundRect( 0, 0, 100, 100, 5, 5 );
sprite.graphics.endFill();

}
}
}


As you can see, we’ve just created a red box, so let’s get this into our ActionScript 3 project.

## Step 2: Binding the SWC

You’ll now need to change the Flex compiler so that it can pick up the new assets SWC you just created. Once you’ve done that, you can change your application’s code to look like this:

	    package
{
import com.flashtuts.swc.Test;

import flash.display.MovieClip;
import flash.display.Sprite;

[SWF( width='600', height='400', frameRate='30', backgroundColor='#FFFFFF' )]

public class App extends Sprite
{
public function App()
{
var rect:MovieClip = new SimpleRoundedRect();

//rect.scale9Grid = new Rectangle( 10, 10, rect.width - 20, rect.height - 20 );
rect.width = stage.stageWidth;

var redRect:Sprite = new Test();

}
}
}


There you’ll see your red rectangle! Simple eh?

## Conclusion

Now a lot of people may argue that SWCs are not needed, but they help designers and developers to work in sync without stepping on each other’s toes. They protect your code and they’re a good way to share visual assets such as preloaders and graphics. While FXGs are much better, until Flash Player 10 picks up, SWCs are the standard when it comes to creating production web sites that need to be scalable, both in terms of project timelines and visual components.

Tags: Tips
• Deoxys

Great tutorial for beginners, I love it. Thank you so much!

• Kevin Minke

Great tutorial I really enjoyed reading this. I would like to know what you might do to use a SWC in Flash CS4 as well as with AS2. A lot of my projects are for the government and we have to low end our work sometimes down to Flash Player 7. Is there a way to use SWCs with this version of the Player to streamline our process?

• http://www.ahmednuaman.com Ahmed Nuaman

Well since you’re using the Flash IDE to compile the AS2, well at least I assume you are, I would just place them in the Library and then you can access them in your class files. I totally understand where you’re coming from, when we had to do stuff for YouTube and Google prior Oct 08, everything had to be in AS2, so we’d use the FLA to store fonts, graphics, etc… and create our classes using the Document class setting.

• Kevin Minke

Cool, thanks for the reply.

• André

Great tutorial, but the penetration of Flash Player 10 is already greather tham 80%, its not more because most people are still using FP9 instead of FP10, so the users dont need to upgrade the version, but i think that until end of july the penetration must be more tham 90%, but i know that you should have done this tutorial before june.

It´s a great work!! thanks so much!!

• http://www.dsaportfolio.com.br Diego SA

Cool! Very well explained and gonna be so useful for me. Before today SWC was something like “WFT?” for me. But now I got it. It was a suck to keep every Flash movie element inside a FLA. The file size always bothered me somehow for being too huge. It’s like a will for punch my monitor. Well, looks like I’ll have to try it anyway, like obliging myself, hehe. Thanks a lot!

• http://www.msdevstudio.com Mário Santos

Great article!
Some times we forget how important are the SWC’s, not only to simplify things but also to obtain more extensibility on your projects. You can distribute your code free but protect your code, you can expand other developers librarys almost as they belong to flash/flex.

Most times i use them for preloaders, and like in this case, visual assets.

Congrats!

• http://www.pv3dzone.com Tim

Nice tut….but I am still trying to understand something though. You say in your article… What’s the Difference Between SWCs and FXGs? Is the argument really that cut n dry…what about embedding compiled SWFs.

package {

import flash.display.MovieClip;

[Embed (source="flash.swf", symbol="FlashLogo")]
public class FlashLogo extends MovieClip {

public function FlashLogo() {

}

}

}

So I guess what I am asking is… Whats the difference between using SWCs over embedding SWFs

thanks!

• http://www.ahmednuaman.com Ahmed Nuaman

Well yes, you can embed SWFs, but the issue here is workflows, a designer could create a load of SWFs for you if you like, but if they’re working in the Flash IDE, surely it’s then better to create a SWC or FXG (from PS/AI) that you can then just using rather than having to have lots of embed tags for SWFs.

• http://www.brianwiltshire.net Brian

Very cool, Nice one thank you

• http://www.salvager.cn salvager

thanks so much! nice tutorials!

Hi and thanks nice tutorial. I’m using the same technic using flash for assets, my little flex project library (moslty utlity wrappers for the sake of using reusable code) and of course the actionscript project. One day moving my classes from the project I was working on to the flex library project I’ve discovered that all my code was broken because before that into the as project there were the “link” to the swc file generated in flash. Moving my classes to a lib project broken everything because I don’t want to add a “specific swc project” in it. I belive I have to rewrite everything. Did you face this problem and how did you resolve. Is there a convinient safe best way to solve? Can you help me with?

• http://www.ahmednuaman.com Ahmed Nuaman

What I do is have a global shared repo for all my classes. So, for example, I’ve got a folder where I store all my class files and another folder where I store all my SWCs. So when I start a new project, I just link to classes folder and select the SWCs from the folder rather than placing them in the project.

• http://richarddas.com Richard

What if you want to extend the class of an item in the Flash SWC? It seems to cause some kind of override, where FB is not seeing the SWC asset :-/

• militia

Ho about the pre load of the swc – im using fdt and i usualy use a library swf that holds the assets that i preload ion app init then i can use a pree loader to show progress then i call assets from the library swf.

if u use swc i this way how do you show the preloading of assets?

• Pingback: Just an ordinary blog

• Aroon

Cool! Interesting though but it becomes a pain if i have a lot of symbols…
Have an issue>I’m using a lot of symbols in my SWC which have to incorporate 9 scale grid. Is there a way that i can assign the 9 scaling through CSS rather than AS3??

• Pingback: On using SWCs … « NudoruUdon