Perfect loading-vomiting blood sorting!

Source: Internet
Author: User
Tags mymc3
There are three parts:
1. Basics
2. movi1_loader discussion (more in-depth)
3. V2 component problems

I. Basics
If you haven't posted any technical logs for a long time, you will be perfect when you come. Don't be excited. A small loading talk about perfection. I think you will know it when you read it.
I wrote this article as the world's most complete non-Flash beginner loading tutorial.
Reprint Please retain the original address: http://www.awflasher.com/blog? Id = 444

First, I want to explain my motivation for writing this article. I remember a long time ago I said, "The flash without loading is not a complete flash ". I think that sentence may be excited. Because sometimes some flash with less than 10 KB does not need to be loading. But I always think that doing a good loading is to measure a flasher level and even attitude. You ask me why, I can tell you, Because loading is the only one that you don't want to read but all users and customers will see, so you pay attention to loading, it can even contradict your flasher professional ethics!

Some design-oriented friends, I know a lot about it. They have a bad attitude towards loading. They do loading, and they find a ready-made one, and apply it each time, I personally think it is a bad habit. It doesn't mean that I don't advocate code and Component Reuse, but I think there is a lot of problems with loading. I strongly recommend that the flasher who has reached the loading level to view my things. Of course, if you don't even know where to write the flash as, I suggest you get started first.

Well, let's start with the question: how to make loading.

First of all, we must be grateful to Macromedia for its great wisdom. We have provided two excellent functions to make the perfect loading, namely getBytesLoaded and getBytesTotal. I can't remember how to make it happen again. I just want to say that the concept of Frame will fade in real Interactive-Design. Not to mention Scene, it's the Flash failure!

So how does loading work? How can we use these two functions? An important concept should be mentioned here. It is called at intervals. There are multiple call interval methods. The following lists their position and usage in loading production. You are welcome to add:

· SetInterval
Statement:
Function loadCheck ()
{
Var p = getBytesLoaded ()/getBytesTotal ();
If (p = 1)
{
ClearInterval (intervalID); // call the release Interval
GotoAndPlay (someFrame); // start playing
}
}
Var interval = 30; // The value is the refresh frequency.
Var intervalID = setInterval (loadCheck, interval );

I personally do not recommend this method for beginners. Because clearInterval is easy to ignore, and it is terrible to ignore it! If your setInterval is not promptly removed, it means that you will add an unnecessary burden throughout the swf playing process!
In addition, this method is not suitable for controlling the MoiveClip situation (because beginners will find that the MC path is a big problem, and loadCheck itself is a function and is still called by setInterval, it is troublesome to specify a path in loadCheck. Do not count on _ root, which will make your program nonstandard. Do not count on this, because it does not seem ideal to use this in functions; it is best to do nothing, but you often do not dare not write) to achieve better results.

· OnEnterFrame Method
This is my favorite method. It is convenient and intuitive.
Because we often use a MC to reflect a loading progress, such as a progress bar or something more creative, only you can't think of, and you can't do it without it.
So how to use it. First, set the idea. Then give your MC An Instance name, such as loader_mc. At this time, write code on timeline. Remember, it is timeline rather than MC. This facilitates code unification, path unification, management, and searching. Don't just move the code to the button and mc to save a few letters, and then there's something wrong with on (press. Unless you are perfunctory in your work, or you are trying to hand in your homework.
Loader_mc.onEnterFrame = function ()
{
Var getTar: MovieClip = this. _ parent;
Var p = getTar. getBytesLoaded ()/getTar. getBytesTotal ();
Trace (p );
If (p = 1)
{
This. onEnterFrame = null;
GotoAndPlay (someFrame); // start playing
}

}

It's that simple. Remember, referencing MC inside MC's event function is always a very fast thing. Because this can point to the MC itself, you can find all your MC through methods such as this. _ parent!

· The timeline-based cycle
This is a very, very old method. However, you can ask the flashers who have never liked to do loading by themselves. This may be the version they are changing.

The above is relatively simple. There are two more problems.
1. movi1_loader
2. Loader with multiple V2 Components

======================================

Ii. movi1_loader class description

Reference English tutorials and make a lot of original supplements-Neil Webb, neil AT nwebb DOT co DOT uk, http://www.nwebb.co.uk
Reprint please indicate the original post: http://www.awflasher.com/blog? Id = 468

Reading data from external ports is a very important and common task for Flash Application Deployment. In particular, we often need to check the data loading progress. The movi1_loader (MCL) class greatly simplifies this effort. In addition, it allows us to get more needs and reduce the amount of code. We can use a single MovieClip class to load one or more outbound resources to the specified MC or level, or we can create different MCL instances for each loading task.

I decided to complete this tutorial in two parts. First, we will introduce the basic usage of MCL, and then we will introduce how to use a separate MCL instance to read the foreign resources to different MC, and, we will add a listener object to participate in the work. Of course, tasks can be completed without the listener. We will not introduce the listener for the time being, because it will make it easier for you to understand MCL.

First, let's take a general look at the callback functions of MCL, which will be detailed later (aw attachment: callback functions I personally understand are pre-determined by a class group and parameters, method with the specified function) Here we can look at what is called a callback function ):

The callback function of the movi1_loader object:

Event Callback functions (when data types are strictly required, they are not methods. After xiang ):
* MovieClipLoader. onLoadStart ()-triggered when loading starts.
* Movisponloader. onLoadProgress ()-triggered during reading
* Movisponloader. onLoadInit ()-triggered when the first frame after reading the loaded resource is executed
* MovieClipLoader. onLoadComplete ()-triggered when the read foreign port resource has been completely downloaded to the local device.
* Movisponloader. onLoadError ()-This is triggered when an error occurs when an outbound resource is loaded.
* MovieClipLoader. unloadClip ()-removes or terminates a load task from the loaded outbound resource.

Method callback function:
* Movisponloader. getProgress (target: object): object-Progress of reading resources from external ports. The parameter is a MC object (aw attachment: in fact, the Data Type of MC is also an object ). Returns an object that contains two pre-defined attributes (houxiang)

To better understand these callback functions, it is the best way to experiment with them. Of course, MCL is only available after flash 7, so don't forget to release it as the 7 + version number at the time of release. If Flash Player is used directly for debugging, some problems may occur. We recommend that you debug it in a browser (personal opinion: it is difficult to obtain external resources, such as obtaining Internet resources from CERNET, it is best not to debug in IDE)

In our example, we will use an MCL object to read different images and place them in different empty MC. The swf file and image source file to be used in this example will be found at Actionscript.org (personal suggestion: it is not necessary to read the source file after reading this article)

============

1. Create a new Flash document and input the following script at frame 1:
_ Root. traceBox. vScrollPolicy = "on ";
Function myTrace (msg)
{
_ Root. traceBox. text + = msg + newline;
_ Root. traceBox. vPosition = _ root. traceBox. maxVPosition;
}
Here we are creating a tracking debugging mechanism. The debugging (variables) will be output to the text box component. The method "myTrace" is a pre-defined function that helps us smoothly monitor certain information. The second sentence serves to make the text box output the latest monitoring value at any time.

2. Now, drag a TextArea component from the component library to the scenario, and give the appropriate size and Instance name traceBox (corresponding to the above script)

3. Next, we will create a new MC component. Deploy three instances in the scenario and name them myMC1, myMC2, and myMC3 respectively. We will load images or swf films into them and resize them as needed after they are downloaded locally. In fact, artificially changing the size of an image may cause many bad consequences, such as the generation of sertices. However, we will do so to let everyone know how to use the onLoadInit event.

4. Create an MCL object and input the following script in the first frame:
Var myMCL = new movi1_loader (); // create an instance of movi1_loader
Aw attachment: Here I want to explain the translation of objects below. In the comments of the above Code, the foreigner uses the word "instance". In literal translation, the Object is "Object", and the Instance represents "instance ". The former pays more attention to its data type, while the latter pays more attention to its objective existence.

5. Now we can deploy the script at the first frame:
MyMCL. onLoadStart = function (targetMC)
{
Var loadProgress = myMCL. getProgress (targetMC );
MyTrace ("The movieclip" + targetMC + "has started loading ");
MyTrace ("Bytes loaded at start =" + loadProgress. bytesLoaded );
MyTrace ("Total bytes loaded at start =" + loadProgress. bytesTotal );
}
The first line of this function declares a (Object Type) variable. Obviously, the value of this variable is obtained by the getProgress method of the myMCL object. we have introduced the getProgress method just now. here we can see that the returned loadProgress. bytesLoaded is the bytesLoaded attribute of the loadProgress object.
Here I am wondering why an object is returned instead of a specific value. There is a reason for this. Function return value makes the program design more perfect. However, in many cases, we do not return a value. We may return two or more values, even their data types are different. In this way, only objects are returned. This is the simplest and most efficient solution to the problem. The following three myTrace statements echo the previously defined monitoring functions, so that we can see the variables we are interested in.

6. We have deployed the corresponding work for the onLoadStart event. Next we will deploy the work for the above other events. Next, onLoadProgress accepts three parameters: targetMC, loadedBytes, and totalBytes. It represents the target container MC instance, and the read volume and total volume.
MyMCL. onLoadProgress = function (targetMC, loadedBytes, totalBytes ){
MyTrace ("movie clip:" + targetMC );
MyTrace ("Bytes loaded at progress callback =" + loadedBytes );
MyTrace ("Bytes total at progress callback =" + totalBytes );
}

7. Our onLoadComplete method only accepts one parameter, which is the container MC instance. Like onLoadStart, we use the getProgress method to return the read status.
MyMCL. onLoadComplete = function (targetMC)
{
Var loadProgress = myMCL. getProgress (targetMC );
MyTrace (targetMC + "has finished loading .");
MyTrace ("Bytes loaded at end =" + loadProgress. bytesLoaded );
MyTrace ("Bytes total at end =" + loadProgress. bytesTotal );
}

8. The onLoadInit method starts execution only after all loaded content is downloaded to the local container MC. This will allow you to better control the attributes of the loaded content. The selected image is very large, so that we can see the reading process more clearly, and I also want to trim the size of the loaded image so that it can be displayed in full.
MyMCL. onLoadInit = function (targetMC)
{
MyTrace ("Movie clip:" + targetMC + "is now initialized ");
TargetMC. _ width = 170;
TargetMC. _ height = 170;
}

9. There is also a callback method onLoadError. If an error occurs, it is triggered. As a good programmer, when deploying well-developed applications, it is essential to avoid errors!
MyMCL. onLoadError = function (targetMC, errorCode)
{
MyTrace ("ERRORCODE:" + errorCode );
MyTrace (targetMC + "Failed to load its content ");
}

10. well that's the hard work out of the way. now we just have to load the files in to their respective targets, using loadClip, and passing it two arguments: the location of your file, and the destination movieclip for the file to load in.
10. Finally, we have deployed the most complex tasks. Next, we only use the loadClip method to read the content we need. The two parameters of the loadClip method are the address of the outbound resource and the instance of the container MC.
MyMCL. loadClip ("http://www.yourdomain.com/test1.swf", "_ root. myMC1 ");
MyMCL. loadClip ("http://www.yourdomain.com/test2.swf", "_ root. myMC2 ");
MyMCL. loadClip ("http://www.yourdomain.com/pic.jpg", "_ level0.myMC3 ");

You can select a relative path. Note: path relativity is also a big problem. When SWF is referenced in HTML outside the local path, it follows the path where HTML is located! This is ignored by many Flash tutorials. Therefore, sometimes absolute paths also benefit from absolute paths. [Download the source file with the path problem. It will be clear after the download]

All debugging work should be done in the browser rather than in the IDE. The Script output mode must be as2.
Remember, for everything to work properly you need to be testing throuhg a browser (and preferably on line so you can see the files loading in real time ). you also need to be exporting your code as ActionScript 2.

In the second part of this tutorial I'm going to show you how to use the movisponloader class in a real-world situation, in order to solve a common problem when assigning event handlers to MovieClips dynamically.
Next, I will introduce how to call MCL in real time. To adapt to more applications, we often work dynamically for MCL.

Aw Voiceover: Sometimes, we write:
1. var mcl: movi1_loader = new movi1_loader ();
2. var mcl = new movi1_loader ();
It is found that the first method cannot create event methods such as onLoadStart for MCL. This is a problem generated by the compiler based on the data type of the specified variable. Some osflash friends gave some useful ideas. I also found that this problem involves the Flash internal Event Response Mechanism. I may introduce it as follows:
Three Event Response Mechanisms of Flash
=====
1. Simple callback functions, the oldest one;
2. listener, ASBroadcaster, and FlashMX;
3. Event interceptor, EventDispather, FlashMX2004 Era

Here, MCL uses the second mechanism, while the entire V2 component uses the last mechanism.
Note: The above method only contains the getProgress method!
Intrinsic class movi1_loader
{
Function movi1_loader ();

Function addListener (listener: object): Boolean;
Function getProgress (target: object): object;
Function loadClip (url: String, target: object): Boolean;
Function removeListener (listener: object): Boolean;
Function unloadClip (target: object): Boolean;
}
In my opinion, 1 and 2 can be used when data types are not strictly required.

The following describes how to use a listener to detect MCL events. Before that, we solved the most common problem. We often see people asking questions in the Forum:
Reference
Hello everyone, I dynamically created some MC and assigned them an event handle (FLAG) one by one ). Then, I read the external resources into them. However, these allocated event handles are no longer working!
Then, the questioner usually posts a mess of code and calls for help.

Then, let's first analyze the cause of this error: When the outbound resource is loaded into a MC, the MC will reinitialize. This means that any pre-developed code will be overwhelmed. There is no related trouble for developers to manually arrange MC on the stage, because any code that is directly written to MC through onClipEvent can be reinitialized. The dynamically created MC performs the above "initialization", because we configure the Event code for them at runtime.

How can we avoid this problem? In fact, there are too many methods, and many forums have discussed them in great detail, so I will not go into detail.

You may still remember the introduction just now, "it is very important and common to read data from external ports to participate in Flash Application Deployment. In particular, we often need to check the loading progress of these data"

We have already introduced several callback functions of MCL, so we will not go into details here. Now we have created a thumbnail-Based Image Browsing System. We will read some JPG images from the outside and put them into the dynamic deployed MC. In addition, we hope that all these dynamically established MC events have their own onPress events. We allocate events to external resources after MC loads them.

Before we start, I would like to remind you to pay attention to some frequent omissions: we must set it to a version later than Flash7 + AS2 during release. Secondly, use a browser to test your performance, rather than IDE; otherwise, you will get strange results.

Now we start to compile the code, and you will find it much simpler than you think.

1. Create a new Flash document.

2. Find four 100*100 pixels thumbnails.

3. Create a dynamic text box, which is about 300*300 pixels. Use the 12-digit font and make it realistic, so that we can better monitor it. Don't forget to set it to multiple rows.

4. Create a x pixel rectangle, convert it to MC, and then remove it from the scene. At this time, he has already appeared in the library. In the library, set its link name to "img" and make it "export at the first frame ". In fact, this rectangle will be replaced when external resources are loaded. Now it is only for debugging convenience.

5. Create a layer above the layer where the textBox text box is placed. This layer is used to place our code.
Stop ();

6. Now we define an MCL instance and a basic object as our listener:
MyMCL = new movi1_loader (); // define movi1_loader
MyListener = new Object (); // define listener

7. Next we will use a listener to listen on the onLoadComplete event. The role of this event has been mentioned above. Now we will give it to the listener object instead of the MCL instance. Of course, when we finally need to return the listener object back to MCL (to listen for its callback function), the effect is what we need.

Remember, it is safe and reliable to deploy event tasks on MC only when the read is complete! Therefore, this onPress event is deployed to MC only when onLoadComplete is triggered:
MyListener. onLoadComplete = function (targetMC ){
Debug. text + = "loading of" + targetMC
+ "COMPLETE" + newline;
TargetMC. onPress = function (){
Debug. text + = newline
+ "TargetMC =" + targetMC. _ name;
}
}

Note: several lines of the above Code are artificially interrupted, but this does not affect the effect.

You may have noticed that the Instance name of MC is passed to onLoadComplete as a parameter identity when onLoadComplete is triggered, so it is very convenient for us to control this MC. For example, you can click MC to check whether the event is successfully deployed to MC.

8. Now we create a function that contains a simple loop to deploy the MC in the scenario. In addition, the loadClip method is used to promptly allocate a task for each deployed MC to read the foreign port resources. The Code is as follows:
Function initClips (){
For (I = 1; I <= 4; I ++ ){
This. attachMovie ("img", "img" + I, I );
This ["img" + I]. _ x = I * 110;
MyMCL. loadClip ("0" + I + ". jpg ",
This ["img" + I]); // code wrapped
}
}

9. This is basically done. Now, the rest of our work is to register the listener and call related functions and methods as needed. The code is reflected in the following two lines:
MyMCL. addListener (myListener );
InitClips ();

Note the order here. Our listener object is applied to the MCL instance before calling the initClip () function. Now our MC onPress event can work smoothly, because when the image is fully read, the event will be allocated. Our code is also very concise. We no longer need to create a troublesome loop for loading. movi1_loader helped us complete all the work!

The complete code is as follows:
Stop ();
MyMCL = new movi1_loader ();
MyListener = new Object ();
MyListener. onLoadComplete = function (targetMC)
{
TargetMC. onPress = function ()
{
Trace ("pressed ");
}
}

Function initClips ()
{
For (I = 1; I <= 4; I ++)
{
This. attachMovie ("img", "img" + I, I );
This ["img" + I]. _ x = I * 110;
MyMCL. loadClip (url, this ["img" + I]);
}
}
MyMCL. addListener (myListener );
InitClips ();

So far, you should believe that MCL is indeed a rare good thing, right? :)

====

Iii. Problems Related to v2 Components

V2, love, hate! Here we will introduce the loading Problem of the V2 component project.
Reprint please indicate the original post: http://www.awflasher.com/blog? Id = 468

The V2 component has been controversial since its launch and is generally summarized as follows:

Advantages:
· The interface is more beautiful and unified than V1 components, and the human-computer interaction mode is improved.
· All are deployed using object-oriented scripts

Disadvantages
· Bulky, it is embarrassing to develop small applications that only use one or two components

The message mechanism replaces the original AsBroadcast mechanism with the EventDispather message broadcast mechanism. As a result, many people will not use it at all.

I will not discuss more here. Let's talk about loading first. Products that contain a large number of v2 components must be loading, for example, the blog tips on the left of aw's blog. However, every loading operation may be difficult. That is, the bulky volume is all put into the first frame for export, which leads to the remote loading effect of some SWF files containing v2 components within kb.

The solution is not useless either. It is simply summarized as three steps:

1. Remove "Export in first frame"
Http://www.awflasher.com/blog/attachments/200603/24_153106_v2linkage.gif

2. Set "Export frame for classes" during release. This is very important!
Http://www.awflasher.com/blog/attachments/200603/24_153056_v2exporter.gif

3. Set the container mc as follows for the swf file with V2 read from the external Port:
Loader_mc. _ lockroot = true;

Now, you can rest assured that you can enjoy the wonderful and bulky V2 components ~!

This series of articles:
1-[technology] originality-perfect loading-perfect in the end [Foundation]
Http://www.awflasher.com/blog/article.asp? Id = 444
This section describes the basics of loading.

2-[technology] originality-perfect loading-perfect final [Weapon]
Http://www.awflasher.com/blog/article.asp? Id = 468
Describes in detail the use of the movi1_loader class and some principles.

3-[technology] originality-perfect loading-perfect in the end [burden reduction]
Http://www.awflasher.com/blog/article.asp? Id = 470
It mainly solves the loading related to v2 components. The original figure is shown. Now, the series of tutorials are over, so there should be no more loading troubles! :)

 

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: info-contact@alibabacloud.com 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.