Key Points of loading SWF using Flex

Source: Internet
Author: User
Tags ranges

Today, I spent most of my time working with flash and flex3. I would like to summarize my experiences:
1) if you use Embed to embed SWF, flex3 only supports SWF created by flashcs2.
2) If it is loaded through loader, only the SWF of as3 can be controlled after loading (this is the opposite of the first point. It took me a long time to figure out these two points, khan !)
3) To directly load data to flex, the class must inherit uicomponent, which is like the displayobject must be inherited in flash.
4) if you want to package flash components for flex, use flexcomponentkit to export MC to SWC. After SWC is configured to the library path in flex, the corresponding component can be used as a level-1 Public indicator in flex. If MC is bound to a class, the corresponding class inherits uicomponent.


A corelib package in googledocs is not very practical (I wrote trim myself some time ago, which is a waste of time). I am tired of reading e files for future reference.
// Image phase usage
Import com. Adobe. Images. jpgencoder;
Public Function submit (): void {
VaR Encoder: jpgencoder = new jpgencoder (80 );
VaR Bytes: bytearray = encoder. encode (getbitmapdata ());
VaR request: URLRequest = new URLRequest (upload_page );
// The data value is the bytearray of the image encoding data;
Request. Data = bytes;
Request. method = urlrequestmethod. post;
// This is the key, and the content type must be the following file stream form;
Request. contenttype = "application/octet-stream ";
VaR Loader: urlloader = new urlloader ();
Loader. Load (request );
// Encryption usage
Import com. Adobe. crypto. sha1;
Trace (sha1.hash ("132 ″));

// The utils package is a complex lock, all of which are static methods.
Import com. Adobe. utils. arrayutil;
Arrayutil. arraycontainsvalue (ARR, value); // whether arr contains value
Arrayutil. arraysareequal (arr1, arr2); // whether arr1 and arr2 are equal
Arrayutil. copyarray (a); // deep copy
Arrayutil. removevaluefromarray (ARR, value); // Delete the value

Import com. Adobe. utils. stringutil;
Stringutil. beginswith (str1, str2); // determines whether str1 starts with str2
Stringutil. endswith (str1, str2); // whether str1 ends with str2
Stringutil. ltrim (STR); // remove the left space
Stringutil. rtrim ();
Stringutil. Trim ();
Stringutil. Remove (str1, str2); // Delete str2 from str1
Stringutil. Replace (input, replace, replacewith); // replace Replace in input with replacewith
Stringutil. stringsareequal (S1, S2, casesensitive); // check whether S1, S2 are equal, and casesensitive is case sensitive

Import com. Adobe. utils. dateutil;
Dateutil. comparedates (D1, D2); // compare, D1> D2 returns-1, = returns 0, <returns 1
Dateutil. getampm (d); // returns am or PM
.... The functions are comprehensive and too many functions are available. I still have a few questions.

Import com. Adobe. utils. numberformatter;
Numberformatter. addleadingzero (5); // return the number of zeros, for example, 1 to 01.

Import com. Adobe. utils. intutil;
Intutil. tohex (n, bigendian); // in hexadecimal notation, the value of bigendian is 0 after completion or 0 before completion.
Intutil. rol (n, m); // n shifts the M bit right (bit operation)
Intutil. ror (n, m); // shift left

Import com. Adobe. utils. dictionaryutil;
Dictionaryutil. getkeys (d); // obtain the key name.
Dictionaryutil. getvalues (d); // obtain the value.

Import com. Adobe. utils. xmlutil;
This will not be used yet. I will try it later, and the XML of as3 will be perfect.

Corelib package

Cross-origin flash call problems
Due to security sandbox restrictions, files (SwF, XML, etc.) in different domains cannot be called each other by default. for example, Flash Under Domain A cannot access XML under Domain B. unless B's domain name is in the root directory of "crossdomain. the XML file contains the domain name. however, the following problems exist:

1) the root directory cannot be modified.
Solution: Allow crossdomain in as3. XML is not in the root directory. In this case, security is required. loadpolicyfile ("”); this method is used to specify. of course, only crossdomain. the directory where XML is located is accessible.

2) crossdomain. xml cannot be added.
Solution: If the SWF file is to be read, you only need to add flash to the main function. system. security. alldomain (". but what if it is other types of files, such as XML files? You can read B .swf from xmlto B (add flash. system. Security. alldomain ("A") to B). Then, copy B .swfin a.swf, and then read the XML in B .swf. Similar:
_ Mc paievent.tar get. content as sprite;
Trace (_ Mc ["Var"]);

Comparison between loader and urlloader
In as3, loader and urlloader are two classes that are easy to confuse:
Application Scope
Loader: SwF, image (JPG, PNG, GIF)
Urlloader: Text File (XML, PHP, JSP ...)

Loader. contentloaderinfo. addeventlistener (event. Complete, loadcomplete );
Private function loadcomplete (Event: Event)
{Trace ("done"); addchild (loader );}

Xmlloader. dataformat = urlloaderdataformat. text;
Xmlloader. addeventlistener (event. Complete, xmlloaded );
Private function xmlloaded (Event: Event)
Try {myxml = xml(event.tar get. data); area. Text = myxml ;}
Catch (E: typeerror) {area. Text = "load faild:/N" + E. Message ;}


As3-lattice text

The above is a little thing made in the past two days. It can describe the input text with a dot matrix and store the information in an array. Then, use this array to generate "text". These "text" can be composed of any sprite and can be animated at will.

Thanks to everyone's kindness, we put the source files here for you to download. In order to facilitate future expansion, I use the observer design mode and hope it will not confuse everyone.
Source File Download

Interaction between JavaScript and flash
Swfobject has briefly introduced how to use swfobject to insert Flash into the page and how to transmit parameters to flash by JS at the beginning, and how Flash calls functions in Javascript during runtime. This section describes how to transfer parameters to each other in Javascript during runtime and control flash playback.

Source File Download

In fact, JS can directly control flash playback, mainly through the following methods:
Play () -------------- play an animation
Stopplay () ------------ stop an animation
Isplaying () ------------ is the animation playing?
Gotoframe (frame_number) ------ jump to a frame
Totalframes () ----------- get the total number of animation Frames
Currentframe () ---------- return the number of frames of the current animation-1
Rewind () ------------- make the animation return the first frame
Setzoomrect (left, top, right, buttom) --- enlarge the specified area
Zoom (percent) ---------- change the animation size
Pan (x_position, y_position, unit) ---- enables the animation to pan in the X and Y directions.
Percentloaded () ---------- return the percentage of animation loaded
Loadmovie (level_number, PATH) ---- load Animation
Tgotoframe (movie_clip, frame_number)-movie_clip jump to the specified number of frames
Tgotolabel (movie_clip, label_name) -- jump to the specified tag
Tcurrentframe (movie_clip) ----- return movie_clip to the current frame-1
Tcurrentlabel (movie_clip) ------ return the current movie_clip label
Tplay (movie_clip) --------- play movie_clip
Tstopplay (movie_clip) -------- stop playing movie_clip
Getvariable (variable_name) ------ get the variable
Setvariable (variable_name, value) ---- variable assignment
Tcallframe (movie_clip, frame_number)-call specifies the action on the frame
Tcalllabel (movie_clip, label) ------ call specifies the action on the label
Tgetproperty (movie_clip, property) --- get the specified attribute of movie_clip
Tsetproperty (movie_clip, property, number)-set the specified attribute of movie_clip

Read the rest of this entry»

Creating and using components in Flash
Here, we will briefly introduce how to create and use the custom components in flash. for work reasons, I use as2 and as3 should be similar.
Creation of component
1. Create a class file, such as classloader. This file implements the main functions of the component. It can call other classes, such as CN. adamstudio. effects. textanimation (this class can be a simple trace). These classes are automatically packaged into components.

// Classloader class:
[Iconfile ("spidercore.png")];
Class classloader extends movieclip
Public Function setsize ()
_ Width = 18;
_ Height = 18;

Public Function donothing (): void
// Trick the compiler into including
// The textanimation class in the component.
CN. adamstudio. effects. textanimation;

2. Create a FLA file, such as swc_generator. Create a movieclip, such as SWC, and set it:

3. Right-click the MC in the database and choose "component definition…" from the right-click menu ...". The settings are as follows:

4. This icon is a new graphic icon. It will be displayed on the database panel and stage in the future.

5. Right-click the MC in the database and choose "Export SWC file…" from the context menu ...", Save the SWC file.

Use of components
1. Merge the generated SWC file:
C:/Documents and Settings/user/Local Settings/Application Data/Adobe/Flash CS3/en/configuration/components/SWC

2. Create a flash file, such as test. fla. after re-opening the component panel in flash, we will find the SWC file in which the volume is stored in the SWC directory. drag it to the stage and delete it on the stage. (only need it in the library ).

3. Add code to the first frame:
Import CN. adamstudio. effects. textanimation;
VaR textani = new textanimation;

Even if the local computer does not have CN. adamstudio. effects. textanimation, the program can still run because it is already included in the SWC file.

Note: Select as2 for the output settings of swc_generator.fla and test. fla; otherwise, the correct result cannot be obtained;

Source File Download: source file

As2-create a subclass of movieclip
When performing visual representations in flash, you often need to create a subclass of movieclip. The following is a good framework:

Avatar subclass:
Class CN. adamstudio. Avatar extends movieclip
// Defines static variables for initialization
Public Static Var happy: Number = 0;
Public Static Var sad: Number = 1;
Public Static Var idle: Number = 2;

// Defines static methods for creating your own instance
Public static function createavatar (Name: String, target: movieclip, depth: Number, X: Number, Y: Number): Avatar
VaR AV: Avatar = Avatar (target. attachmovie ("avatarsymbol", name, depth ));
Av. INIT (x, y );
Return AV;

// Set the coordinates of the Instance
Public Function Init (X: Number, Y: Number): void
Setstate (avatar. Happy );
This. _ x = X;
This. _ y = y;

// Initialize the instance
Public Function setstate (newstate: Number): void
Switch (newstate ){
Case avatar. Happy:
This. gotoandstop ("happy ");

Case avatar. Sad:
This. gotoandstop ("sad ");

Case avatar. Idle:
This. gotoandstop ("idle ");
Note: static variables and static functions are optional and can be changed according to requirements.

In the main document:
Import CN. adamstudio. Avatar;
VaR AV: Avatar = avatar. createavatar ("Avatar", _ root, 0,200,200 );

The feature and advantage of this method is that the static method of subclass is used to instantiate the subclass of movieclip, which is very concise in the main document.
Source File Download

As-positive and negative random number Algorithm
I used the following methods:
Math. Random () * 2-1
Today I see an interesting method:
Math. Random ()-math. Random ()

As3 mouse coordinate Summary
The mouse is the main interaction factor in flash. It is often necessary to detect the mouse event (as3 mouse event summary) and get the mouse coordinates. The acquisition of mouse coordinates can be divided into two different situations: document class and subclass.

1) if it is on the time line axis or the document class, use:
Stage. mousex and stage. Mousey

2) use:
_ Sprite. mousex and _ Sprite. Mousey
Here we get the coordinates of the mouse relative to _ Sprite. If you need coordinates relative to the stage, use localtoglobal, for example:
VaR mousepoint: Point = new point (_ Sprite. mousex, _ Sprite. Mousey );
Mousepoint = _ Sprite. localtoglobal (mousepoint );
Trace ("stage coordinates:" + mousepoint );

Note: Do not forget to use the above Code to import flash. Geom. Point;

As3 exercise-round-trip exercise

This is an as3 exercise today. It is mainly used in combination with acceleration and deceleration. Some strange phenomena may occur when there are more particles, for example, occasionally several particles flash in the original position. The execution sequence of flash code may be more relevant.

As3 runtime error description
1000 the system memory is insufficient. The available system memory cannot meet the needs of Flash Player code compilation. Disable some running applications or processes on the system.
1001 no implementation method _.
1002 number. The toprecision range is 1 to 21. Number. tofixed and number. toexponential ranges from 0 to 20. The specified value is not within the expected range. The specified value is not within the expected range of the precision parameter. Number. toprecision ranges from 1 to 21. Number. tofixed and number. toexponential ranges from 0 to 20.
1003 the radix parameter must be between 2 and 36; get _. The value passed for the radix parameter of the method or attribute is less than 2 or greater than 36. Please pass a value between 2 and 36 as the radix parameter.
1004 call method _ For incompatible objects _. The method to be called is not applicable to the specified object. If you have copied a prototype function from one object to another and then called this function, but the type of the target object is different from that of the original object, this error occurs. Make sure that the target object is of the same type as the original object. For more information, see Chapter 3rd in ecmascript language specification (ecmascript Language Specification) 15th.
1005 The array index is not a positive integer (_). Try to use a group of non-positive integer index value members. Only a positive integer is passed as the index value of the array.
1006 _ is not a function. This error occurs when you try to call a function that does not exist. Make sure that the correct function is being called and this API has not been changed since corner 2.0. In addition, make sure that you are using the correct object. For example, this error occurs when you use the following code (the variable big is called due to the last line error and the variable BLG is not called ):
VaR BLG: String = "foo ";
VaR big: SPRITE = new sprite ();
VaR error: Int = big. Length ();
1007 try to instantiate non-constructor.
1008 _ the reference is not clear; Multiple matching bindings are found.
1009 properties or methods referenced by null objects cannot be accessed. Objects whose calculation result is null can not contain any attribute. This error may occur in some unexpected (even valid) situations. The following code creates a Sprite object is used as an example. Since this sprite object has never been added to the display list (using the addchild () method of the displayobjectcontainer object), its stage attribute is set to null. In this case, this example generates this error because the stage attribute of the sprite object cannot have any attribute: Read the rest of this entry»

Air-Latest rssreader (based on flash)
After a long time of effort, rssreader 2.0 was finally made with Flash CS3 + as3 + air beta2.
Some time ago, I made a wordpressreader using HTML + Js. Although I implemented automatic upgrades and other cool functions, the interface is still relatively simple.
Air reading blog RSS-Adobe AIR beta2 practices
Wordpressreader 1.1 Completed

This rssreader is based on actionscript3, with a much better interface and a significant improvement in user experience.
Initial interface:

Article reading interface:

Implemented functions:
1. Read XML documents from the server;
2. Store the read XML document to the built-in local database SQLite of air !!! (Cool !)
3. Determine the network connection status. If the network connection is smooth, read and display the article title in an animated form, and refresh existing articles in SQLite with the latest article. If the network is disconnected, read and display the articles stored in SQLite;
4. displays the title of an animated article in an animation;
5. Switch between custom events, article titles, and article content.

It is useless to say more. You will know how strong Adobe AIR is after a try!

Flash-navigatetoURL replaces geturl
In as3, geturl is replaced by navigatetoURL. In my opinion, the biggest benefit of navigatetoURL is the convenience of passing parameters. If there are deficiencies, it is said that the pop-up window will be intercepted by the browser. Use: externalinterface. call ("window. open ", winurl," "); to avoid this, but this is done by calling JS, it must be supported by the browser and JS can be used (not tested ).
In addition, it is found that when using navigatetoURL in Adobe AIR To open a connection, it can only be opened in a new window (not blocked by the browser), "_ Self", "_ parent ", "_ top" is useless. in addition, they all call browsers, rather than opening them in air.

The usage is as follows:

Package {
Import flash. display. Sprite;
Import navigatetoURL;
Import URLRequest;
Import urlvariables;

Public class navigatetourlexample extends sprite {

Public Function navigatetourlexample (){
VaR URL: String = ";
VaR variables: urlvariables = new urlvariables ();
Variables. examplesessionid = new date (). gettime ();
Variables. exampleuserlabel = "Your Name ";
VaR request: URLRequest = new URLRequest (URL );
Request. Data = variables;
Try {
NavigatetoURL (request );
Catch (E: Error ){
// Handle error here

Flash-how to change the transparency of dynamic text?
Because the system font of Flash does not support transparency directly, we have to embed the font or filter class to solve this problem. It is useless simply by changing the Alpha of the dynamic text or the Alpha of the MC it is made in.

1. embedded font
This method is the easiest. Select the dynamic text box and click the embedded button ("embed") in the attribute panel. After the button is pressed, select whether to embed all the font or only some characters. But the cost is that the file will become larger, especially when the Chinese font is embedded, it is absolutely a nightmare. Of course, it is very convenient to embed a few simple characters such as the download progress 0-9.

2 Filter
This is learned from blueidea. It adds a filter to the dynamic text, even if it is an empty filter.
Code in as3
// Create dynamic text
VaR my_txt: textfield = new textfield ();
My_txt.autosize = textfieldautosize. Left;
My_txt.background = true;
My_txt.border = true;
My_txt.text = "Hello world and welcome to the show .";
// Define a filter
VaR txt_blur: blurfilter = new blurfilter (0, 0, 0 );
My_txt.filters = [txt_blur];
My_txt.alpha = 0.5;
// Add dynamic text
My_txt.x = my_txt.y = 50;
Addchild (my_txt );
Code in as2
Import flash. Filters. blurfilter;
VaR txt_blur: blurfilter = new blurfilter (0, 0, 0 );
This. createtextfield ("my_txt", 1,100,100,300,100 );
My_txt.text = "ddggdgdgdgdg ";
My_txt.filters = [txt_blur];
My_txt. _ alpha = 50;

3 bitmapdata and colormatrixfilter
According to hbro, bitmapdata and colormatrixfilter can also achieve the translucent Effect of dynamic text. However, I am too lazy to find a way to be lazy. I will study it later, haha.

Summary of mouse events in as3
Mouse events and mouse positions (as3 mouse coordinate summary) are the most important ways of human-computer interaction in RIA. Recently, when we made a system produtshow for a dynamic product presentation, we found that we had a superficial understanding of mouse events. Now productshow is complete. Here we will summarize the issues that need to be paid attention to when using mouse events:
1 mouse events include mouse_over, mouse_move, mouse_down, mouse_up, mouse_out, mouse_wheel, and mouse_leave. The first six events are from flash. events. mouseevent class. The last mouse_leave is from flash. events. event, you must pay attention to this problem when importing the class package, because it takes a long time for me to debug and discover the problem.
Mouse_over-triggered when the mouse moves over the target object. It can be used to simulate the mouse over effect of the button;
Mouse_move-triggered when the mouse moves above the target object, mainly used for judgment. For example, you can determine whether the instance is within the permitted range when you drag an instance. If the instance is exceeded, immediately stop dragging or reset the instance coordinates;
Mouse_down-triggered when the mouse is pressed over the target object. Note: This function is triggered only when the left mouse button is pressed, and neither the right-click nor the scroll wheel is triggered. It is not triggered when you press the left mouse button outside the target object and move it over the target object;
Mouse_up-triggered when the mouse is released on the target object. Note: This function is triggered only when the left mouse button is released, and neither the right-click nor the scroll wheel is triggered. It is not triggered when you press the left mouse button on the target object and move it out of the target object to release it. However, when you press the left mouse button outside the target object and move it to the target object to release it, it will trigger.
Mouse_out-triggered when the mouse moves outside the target object.
Mouse_wheel-triggered when the scroll wheel is rotated over the target object.
Mouse_leave-triggered when the cursor leaves the stage (stage. addeventlistener (event. mouse_leave, leavehandler );). After a custom mouse is used, when the mouse leaves the stage, the mouse_leave event is triggered, and the custom mouse can be hidden to avoid staying on the stage.

2 mousechildren. When the target object contains a child instance, the mouse row is a child column instead of a target object. If you use cursor. mouseenabled = false; you can use the target object to better adapt to mouse behavior.

3. mouseenabled. When an instance overlaps, the instance above the display list always has a higher priority than the instance below to sense mouse behavior. Use cursor. mouseenabled = false when you want the lower instance to sense mouse behavior. This is often used after a custom mouse to remove the interference of the custom mouse on the mouse behavior, because the custom mouse is always under the mouse, other instances can no longer sense the mouse changes.

In addition, maybe double_click should also be used as a mouse event, but to use it, you must first set doubleclickenabled to true:
VaR BG: SPRITE = new sprite ();
BG. doubleclickenabled = true;
BG. addeventlistener (mouseevent. double_click, clickhandler );

Differences between typeof, is, and
Typeof, is, and as are used to determine the variable type, but their return values are different. See the following code:
VaR A: Number = 0;
Trace (typeof (a); // output: Number
Trace (typeof (A); // output: String
Trace (A is number); // output: True
Trace (A as number); // output: 0
Trace (A as string); // output: NULL

Differences between null, Nan, and undefined
In fact, null, Nan, and undefined are the default values of the variable. Different variable types give different initial values:
Int, uint-0
String, array, object-Null
Variable type not specified-undefined

Swfobject solves the problem of passing parameters between HTML and flash.
In the article about how to completely abandon Adobe's method of activating ActiveX controls, we have analyzed in detail the problem that using ac_runactivecontent.js provided by Adobe causes the inability to pass parameters between HTML and flash. As prompted by GWD in the Adobe forum, I turned to swfobject for help. Swfobject is a good solution.

Source File: swfobject 1.5

The introduction to swfobject has been detailed in the previous two articles. I will only list a piece of standard applications and some issues not mentioned in the above two articles.

JS Code in HTML
<SCRIPT type = "text/JavaScript" src = "swfobject. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript">
// <! [CDATA [
VaR so = new swfobject ("ascalljs.swf", "mydemo", "500", "400", "9", "# ff6600 ");
So. addvariable ("param1", "parameter1"); // This line is optional, but this example uses the variable and displays this text inside the Flash Movie
So. addvariable ("param2", "parameter2 ");
So.useexpressinstall('expressinstall.swf ');
So. Write ("flashcontent ");
</SCRIPT> <! -- JS functions called by as -->
<Script language = "JavaScript">
// <! [CDATA [
// Adds two numbers, and sends the result back to ActionScript
Function addnumbers (num1, num2)
Result = num1 + num2;
Alert ("3 + 7 =" + result );
Return (result );
</SCRIPT> Read the rest of this entry»

Completely abandon Adobe's method of activating ActiveX Controls
As you know, flash can interact with viewers only when ActiveX control is activated in IE. Otherwise, you must click activate. Flash also provides a "convenient" solution, that is, to publish an HTML file while publishing the SWF file. In this way, flash generates a SWF file, an HTML file containing SWF, and an "ac_runactivecontent.js" file. The HTML file activates the ActiveX control by calling ac_runactivecontent.js. All this is convenient until you want to pass parameters between HTML and flash.
In many commercial websites, the same flash is used to display a large number of different contents (images, videos, or product information). Therefore, parameters must be transmitted to the Flash. There are three common parameter passing methods, but they are all adversely affected by ac_runactivecontent.js.
1 externalinterface: this is a problem that has plagued me for the longest time. According to Adobe's description, this is the best parameter passing method, which can freely and directly transfer parameters or call functions between AS and Js. However, when I used the Adobe sample file, I found that as in IE could not get the JS return value (the bug of externalinterface in IE). After constant attempts, I found that ac_runactivecontent.js was playing tricks, you only need to delete the corresponding code in HTML and <NoScript> </NoScript>.
See the example:
Player8, As2:
Player9, as3:
If the JavaScript code with the ActiveX control activated is included, the return value cannot be obtained in IE. See:
All Source:
2 flashvars:
3. url Transfer Parameters
The latter two methods are more affected by ac_runactivecontent.js, because both methods add code between <NoScript> </NoScript>, among the browsers that JS can run (most browsers can run JS), these codes will not run at all. So it does not work in Firefox or IE!
That is to say, the three common methods for passing parameters between HTML and as are affected by the code that activates ActiveX controls. Therefore, to pass parameters between HTML and flash, you must discard the built-in Flash ActiveX control activation solution!

Alternative solution: For swfobject, refer to swfobject to solve the parameter passing problem between HTML and flash.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.