`

Make an AS3 Flash Component with Custom UI Controls

阅读更多

from: http://studio.barliesque.com/blog/2008/12/as3-component-custom-ui/

 

Make an AS3 Flash Component with Custom UI Controls

 

I’d nearly given up the whole idea, having searched all over the internet only to find dozens of others asking the same questions I’d had, but no one was delivering the answers. Or not all the answers, at any rate.

As seemingly exhaustive as Adobe’s gigantic article by Jeff Kamerer is, many answers were not to be found there. I wanted to make an SWC-based component that did not rely on the UI Component framework — after all, not every component is a UI gadget! I wanted to write a simple class to draw something to the stage, with a few options I could control with my own control panel and see updated with a live preview right on the stage.

Along the way to a solution, I encountered a host of problems getting the control panel to communicate with the authoring tool, and for the authoring tool to communicate properly with the component and the control panel… and then even with all of those problems cleared up, there was still the problem of parameter settings being retained in the finished compiled product. It seems quite clear that several aspects of component creation do not work as they should–at least not when you add a custom control panel into the mix. However, in spite of all the problems, there is a reasonable workaround to make this possible.

Eventually, after a lot of googling about, and a whole lot of trial and error, I managed to piece together this jigsaw puzzle, and can now present to you a method for creating your very own components with custom control panels, all in Actionscript 3, which works for both Flash CS3 and CS4.  In this article, I’ll give you a tour of the code for a simple component and its control panel, with notes on how to make your own components.

 

 CLICK HERE to download the complete source files.

 

THE COMPONENTD

efining Parameters


First, let’s take a look at the source code for the component. Open up “MyComponent.as”  …In order to inform Flash what the parameters for this component will be, we have to include [Inspectable] metadata tags in the class code.

 

 

 [Inspectable (name = "color", variable = "color", type = "Color", defaultValue = "FF0000")]
 [Inspectable (name = "radius", variable = "radius", type = "Number", defaultValue = "10")]

 

 

I’ve placed them right at the top of the class, for easy reference. Both parameters–radius and color–are going to call getter/setters which you’ll find near the end of the file. There are a few important things to notice here:

  •     The name and variable for each parameter MUST be the same
  •     All of the parameters MUST be in alphabetical order
  •     The default values must be set BOTH in the meta-data and the code

Of course these are hardly official requirements for writing a component, and I’m sure there are plenty of components out there that were not written following these rules. However, in order to create this component with a custom user interface in the Component Inspector and with live preview… all three of these rules must be observed.

Note also that the default value for color is represented as a hex string without the leading “#” or “0x”

 

The setSize() Method

Moving on, the setSize() method is where we handle resizing of the component. The Flash authoring tool will automatically call this function for live preview, so it must be defined as public, and with parameters for width and height.

 

 

public function setSize(w:Number, h:Number):void {
	_width = w;
	_height = h;
	draw();
}

private function draw():void {
	_background.graphics.clear();
	_background.graphics.beginFill(_color, 1);
	_background.graphics.drawRoundRect(0, 0, _width, _height, _radius, _radius);
	_background.graphics.endFill(); 

	_tf.text = Math.floor(_width) + " x " + Math.floor(_height);
	_tf.x = (_width - _tf.width) * 0.5;
	_tf.y = (_height - _tf.height) * 0.5 + 2;
}

 

 

Some component source examples I’ve come across have defined a draw() method as protected, with a drawNow() method to provide public access. I have found no requirement for this, except perhaps when working with the UIComponent framework.

Parameter get/set functions

Next, the getter/setter functions for our parameters, color and radius. We need to use getter/setter rather than public properties so that whenever these values change, we can redraw the component.  This will keep the component updated both for live preview and at runtime.

 

 

public function get radius():Number { return _radius; }
public function set radius(value:Number):void {
	_radius = value;
	draw();
}

public function get color():int { return _color; }
public function set color(value:int):void {
	_color = value;
	draw();
}

 

Override width and height

Finally, we must override the getter/setter functions for width and height. If we don’t, then when an actionscript call is used to change the dimensions of our component, it would merely be stretched or squashed.  What we want is to redraw the component with the new size.

 

 

override public function get width():Number { return _width; }
override public function set width(value:Number):void {
	_width = value;
	draw();
}

override public function get height():Number { return _height; }
override public function set height(value:Number):void {
	_height = value;
	draw();
}

 

 

Compile and Test

Let’s compile the component and try it out without any custom control panels, just for starters.  Open up “Make a Component.fla”  You’ll find just one library item, a MovieClip called “MyComponent.”  It’s not quite ready to be compiled as it is.  Double-click the item to open it up on the stage.  You’ll find just one object, called “avatar” which the component code will use for default dimensions and as a simple means of setting font format properties as well as embedding the font.  All right let’s compile…

 

1.In the Library, right click “MyComponent” and click on “Properties”
2.Tick the box: “Export for ActionScript”  Since the class box will have automatically set itself to “MyComponent” it will use our component code.
3.Click OK, and again, right click “MyComponent” in the Library and click on “Component Definition…”
4.As redundant as it is, type “MyComponent” into the Class box here also, and then click OK.
5.Again, right click “MyComponent” in the Library and click on “Component Definition…”

NOTE: The parameters part of this dialog will now show our parameters, radius and color.  Frankly, this dialog was built backwards:  it ought to have filled in the Class from the Properties dialogue, and from that the Parameters.  But that’s not how it works.  What’s more, don’t bother trying to rearrange your parameters using the buttons provided–those changes will be lost.  You see, as soon as you click OK in this dialog, Flash reads in the Class file, searching for meta-data and rebuilds the parameters table…!

 

6.Tick the box: “Display in Components Panel” and click OK.
7.Now right click “MyComponent” one more time and click on “Export SWC File…”
8.Make a new folder in: “C:\Program Files\Adobe\Adobe Flash CS3\en\Configuration\Components” called “My Components” or “Test Components” or whatever you like.
9.Export the SWC file to this foler.
10.Open up the Components panel (ctrl-F7 / -F7)
11.Click the panel options button (the tiny black triangle in the upper right corner of the panel) and click on “Reload”

NOTE: Whenever you re-compile your SWC file, you must reload the Components panel for Flash to load in the updated version.

 

12.You should see the name of the folder you created your component in, so open that and you’ll find your new component.
13.Make a new Flash document where we’ll give the component a try out.
14.Drag the MyComponent from the Library panel onto the stage.  You should see something like this:

 

Tthe avatar has been replaced.  Our component code has been run, right on the stage.

 

15.With the component selected, click on the Parameters tab of the Properties panel.
16.Try changing the parameter values.  Immediately as you change the values, the component updates itself.
17.Save this file as “Test Component.fla” and we’ll come back to it later.

 

 CUSTOM CONTROL PANEL

Something to keep in mind is that our custom control panel will not communicate directly with the component instance. Rather, the control panel adjusts parameter settings in the authoring tool, and the authoring tool in turn modifies the component instance. The component instance receives information via the setSize() method and property setters, and has no means of its own to communicate with either the authoring tool or the control panel. Keeping our parameters in alphabetical order, rather than trying to arrange them in some logical order, allows us to avoid a minefield of problems.

 

Reading Parameter Values

Let’s have a look at the source code for our control panel.  Open up “ControlPanel.as”  Once again, right near the top of the file are references to our parameters:

 

private const PARAMETER_COLOR:String = "fl.getDocumentDOM().selection[0].parameters[0].value";
private const PARAMETER_RADIUS:String = "fl.getDocumentDOM().selection[0].parameters[1].value";

 

These instructions refer to parts of the Flash authoring tool’s user interface using the JSFL language–specifically, the parameters panel of the selected object.  (See below under Further Reading for more details about JSFL.) Notice that the numbering of the parameters follows the alphabetical order we’ve maintained.  Although it’s not required to set these constants, it makes the rest of the

 

public function ControlPanel() {

	color.text = MMExecute(PARAMETER_COLOR);
	if (color.text.substr(0, 1) != "#") color.text = "#" + dec2hex(uint(color.text));
	color.addEventListener(Event.CHANGE, setColorFromText, false, 0, true);
	colorPicker.addEventListener(ColorPickerEvent.CHANGE, setColor, false, 0, true);

	radius.text = MMExecute(PARAMETER_RADIUS);
	radius.addEventListener(Event.CHANGE, setRadiusFromText, false, 0, true);
	radiusSlider.addEventListener(SliderEvent.CHANGE, setRadius, false, 0, true);

	addEventListener(Event.ENTER_FRAME, setControls, false, 0, true);
}

//......................

private function setControls(e:Event):void {
	setColorFromText();
	setRadiusFromText();
	removeEventListener(Event.ENTER_FRAME, setControls);
}

 In the class constructor function, we read the current control panel values and apply them to our controls.  Using the MMExecute() function (which is made available by importing the package: adobe.utils.MMExecute) allows us to execute our JSFL code defined in those two constants above.

The slider and the color picker components’ default parameter values will be applied right after our control panel is instantiated.  Hence, the code to set those controls had to be called from an ENTER_FRAME event listener, so that it would occur after those components had been initialized.

Setting Parameter Values

Whenever parameters are changed, either with the handy slider & color picker, or with the text fields, setting the parameters in the authoring tool requires another simple call to MMExecute():

 

MMExecute(PARAMETER_RADIUS + "=" + value);

	// Which, assuming value is 20, is equivalent to...

MMExecute("fl.getDocumentDOM().selection[0].parameters[1].value = 20");

 

That’s really there is to it.  The remainder of the ControlPanel.as code works like any other Flash form, updating text and components to work together, and using l to MMExecute() to update the authoring tool. The authoring tool in turn sets variables in our component instance to update the live preview.  Now let’s add this control panel to our component…


Compile the Component with Custom UI

    1.Compile the control panel (Shift-F12) creating “Component Control Panel.swf”
    2.Now, re-open “Make a Component.fla” and right-click MyComponent in the Library panel, then click “Component Definition…”
    3/Across from “Custom UI:” click on the Set button.
    4.Select “Custom UI in external .swf file”
        Select “Display in Component Inspector panel”
        Assign the Custom UI .swf file by clicking on “Browse…” and selecting ”Component Control Panel.swf” which we just created.
        Click OK
    5.Click OK
    6.We’re ready to re-compile the component.  Right-click MyComponent and click on “Export SWC File…” and overwrite the older SWC file we created
    7.Update the Component panel by clicking the panel options button (the tiny black triangle in the upper right corner of the panel) and click on “Reload”
    8.Re-open your test file: “Test Component.fla”
    9.Click and drag the updated component from the Coponents panel, into the Library panel.  You should see the dialog: “One or more library items already exist in the document.”  Select “Replace existing items” to update your test file.
    10.Now when you click on a component instance on the stage, the Parameters panel will no longer allow parameters to be set there, but will give you a button to launch the Component Inspector, which is where our control panel will appear.

    NOTE: By choosing “Display in Property Inspector” in step 4, you can get your control panel to appear in the Parameters tab.  However, in this example case, the color picker demands more space than is available there.
   

    11.Try making a few variations of the component on stage and compile your test movie.

 

CONCLUSION

Thanks for reading!  I hope you’ve found this tutorial helpful.  Check out the file “Use the Component.fla” and its base class “UseComponent.as” for various tests which helped me to refine this method and write this tutorial.  There is also an illustration of the one issue, described below, that I have as yet been unable to resolve.  If you should come up with a solution, please be sure to post about it here!


Known Issue:

If I rotate the component on the stage in the authoring tool, its width and height are incorrectly reported as an unrotated bounding box, which will inevitably be larger than the correct dimensions, as shown below:

 

 

 

The selected component shows its correct dimensions as 83 x 17, while the authoring tool shows the incorrect dimensions 70.2 x 70.2.  At runtime, the component is initialized with those incorrect dimensions:

 

 


 [UPDATE]  A solution to this problem is presented by Juan Carlos in a comment that follows this post.


Further Reading:

Read about the [Inspectable] meta-data tag:
http://livedocs.adobe.com/flex/3/html/help…
http://livedocs.adobe.com/flash/9.0/main/…
It seems this information does pertain to AS3 as compiled by Flash CS3+, but I have never found documentation except as it pertains either to Flex or to AS2.

To find out more about JSFL and what you can do with MMExecute(), take a look at this excellent video by Lee Brimelow about creating panels to extend the Flash IDE:
http://gotoandlearn.com/play?id=66

This reference to extending Flash provides full details of JSFL support in Flash:
http://livedocs.adobe.com/flash/9.0/main/flash_cs3_extending.pdf

…and a tutorial on creating FLA-based components:
http://www.flashbrighton.org/wordpress/?p=31

  • 大小: 13.4 KB
  • 大小: 54.5 KB
  • 大小: 27.5 KB
分享到:
评论

相关推荐

    ComponentOne Studio for ASP.NET Wijmo 2012 v3 5/5

    Built with HTML5, jQuery, CSS3, and SVG, Studio for ASP.NET Wijmo controls make your applications suitable for Today's Web. Effortless Application-wide Theming Easily develop a consistent look ...

    ComponentOne Studio for ASP.NET Wijmo 2012 v3 4/5

    Built with HTML5, jQuery, CSS3, and SVG, Studio for ASP.NET Wijmo controls make your applications suitable for Today's Web. Effortless Application-wide Theming Easily develop a consistent look ...

    ComponentOne Studio for ASP.NET Wijmo 2012 v3 3/5

    Built with HTML5, jQuery, CSS3, and SVG, Studio for ASP.NET Wijmo controls make your applications suitable for Today's Web. Effortless Application-wide Theming Easily develop a consistent look ...

    ComponentOne OLAP for Silverlight2012 v3 3/3

    ComponentOne OLAP for Silverlight2012 v3 3/3 一共有 3 个压缩文件,请... With advanced data visualization, editing, layout and navigation controls, Studio for Silverlight will make your OLAP apps shine.

    ComponentOne Studio for ASP.NET Wijmo 2013 v1 2/5

    Built with HTML5, jQuery, CSS3, and SVG, Studio for ASP.NET Wijmo controls make your applications suitable for Today's Web. Effortless Application-wide Theming Effortless Application-wide ...

    ComponentOne Studio for ASP.NET Wijmo 2013 v1 3/5

    Built with HTML5, jQuery, CSS3, and SVG, Studio for ASP.NET Wijmo controls make your applications suitable for Today's Web. Effortless Application-wide Theming Effortless Application-wide ...

    ComponentOne OLAP for Silverlight2012 v3 1/3

    ComponentOne OLAP for Silverlight2012 v3 1/3 一共有 3 个压缩文件,请... With advanced data visualization, editing, layout and navigation controls, Studio for Silverlight will make your OLAP apps shine.

    ComponentOne OLAP for Silverlight2012 v3 2/3

    ComponentOne OLAP for Silverlight2012 v3 2/3 一共有 3 个压缩文件,请... With advanced data visualization, editing, layout and navigation controls, Studio for Silverlight will make your OLAP apps shine.

    ComponentOne Studio for ASP.NET Wijmo 2012 v3 2/5

    Built with HTML5, jQuery, CSS3, and SVG, Studio for ASP.NET Wijmo controls make your applications suitable for Today's Web. Effortless Application-wide Theming Easily develop a consistent look ...

    ComponentOne Studio for ASP.NET Wijmo 2012 v3 1/5

    Built with HTML5, jQuery, CSS3, and SVG, Studio for ASP.NET Wijmo controls make your applications suitable for Today's Web. Effortless Application-wide Theming Easily develop a consistent look ...

    ComponentOne Studio for ASP.NET Wijmo 2013 v1 5/5

    Built with HTML5, jQuery, CSS3, and SVG, Studio for ASP.NET Wijmo controls make your applications suitable for Today's Web. Effortless Application-wide Theming Effortless Application-wide ...

    ComponentOne Studio for ASP.NET Wijmo 2013 v1 4/5

    Built with HTML5, jQuery, CSS3, and SVG, Studio for ASP.NET Wijmo controls make your applications suitable for Today's Web. Effortless Application-wide Theming Effortless Application-wide ...

    ComponentOne Studio for ASP.NET Wijmo 2013 v1 1/5

    Built with HTML5, jQuery, CSS3, and SVG, Studio for ASP.NET Wijmo controls make your applications suitable for Today's Web. Effortless Application-wide Theming Effortless Application-wide ...

    Windows Presentation Foundation Unleashed (2007).rar

    【开 本】 16开 【页 码】 656 【版 次】1-1 Book Description <br> <br>Printed entirely in color, with helpful figures and syntax coloring to make code samples appear as they do in...

    Visual C++ 编程资源大全(英文源码 表单)

    36.zip Folder Browsing Dialog 目录浏览对话框(3KB)<END><br>37,37.zip Font dialog with custom text preview & color 字体对话框中增加字体和颜色的预览(12KB)<END><br>38,38.zip Embedding an ...

    C# Game Programming Cookbook for Unity 3D - 2014

    3.4 User Data Manager (Dealing with Player Stats Such as Health, Lives, etc.)....37 3.4.1 Script Breakdown..........................................39 4. Recipes: Common Components 41 4.1 Introduction...

    stdafx.h代码

    // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for ...

Global site tag (gtag.js) - Google Analytics