Optimize the Display Effect in Java animation Programming

Source: Internet
Author: User

 

Java animation programming has a variety of implementation methods, but the basic principle of their implementation is the same, that is, draw a series of frames on the screen to create a feeling of motion. Java multithreading is a widely used technology in Java animation programming. It plays an important role in controlling the flow of Animation programs and the display effect of animations. The flash and incomplete image in Java animation programming are common problems for Java programmers. Based on the author's application examples, this article describes how to solve these problems by using multithreading, heavy-load update, dual-buffering, image tracking, and other techniques to achieve the best effect of animation display.

 

Java multithreading technology

Introduction to Java multithreading technology

Currently, threads have been used by many operating systems and application development systems. A thread is a single control flow of a program and has the characteristics of a sequential program. However, a thread is not a program, but an execution sequence of the program. A thread has a strong concurrency function. Multiple Threads can be executed simultaneously at the same time. The thread is dynamic and has a certain life cycle, which goes through the process from creation, execution, blocking, to extinction. JAVA supports multithreading in two ways: one is to inherit the Thread class directly, and the other is to implement the runnable interface. The thread class provides thread control methods, such as start (), stop (), run (), suspend (), resume (), and sleep, they can control the thread status.

Design and Implementation of animation threads

To update the screen multiple times per second, you must create a thread to implement an animation loop. This loop tracks the current frame and responds to periodic screen update requirements. An easy mistake for many Java beginners is to place the animation loop in the paint (), occupying the main AWT thread, and the main thread will be responsible for all the plotting and event processing. Therefore, an independent animation thread should be generated to display and update images. For example, in an applet framework, an animation thread is generated when the applet starts (start); when the applet stops (STOP, terminate the animation thread to release the CPU resources it occupies. The following program code ("C1" Code) is the specific implementation of the animation thread:

Public void start () {If (animatorthread = NULL) {animatorthread = new thread (this); // start the animation thread animatorthread. start () ;}} public void stop () {// stop the animation thread animatorthread = NULL ;}

When an animation thread is terminated, the STOP () method of the animation thread is not called, but the animation thread is set to null. If you call the stop () method of the thread directly, the thread will force the thread to terminate all execution tasks, and sometimes bring bad results. If the animation thread is set to null, the thread exits naturally in the run () method because it does not meet the loop conditions. In this way, the animation program is further optimized.

 

Reload Update () and double buffer technology to eliminate flickering

In Java, animation flashes for two reasons: one is that the repaint () method is called when the next frame is displayed, and the repaint () method is called, to clear the entire background, call the paint () method to display the screen. In this way, what the user sees in the short interval between clearing the background and drawing the image is blinking. Another reason is that the painting () method requires complex calculation. It takes too long to draw each frame, and the pixel values in the image cannot be obtained at the same time, the animation is generated at a frequency lower than the refresh frequency of the monitor, resulting in flickering.

The following two methods can be used to obviously eliminate or reduce flickering.

Overload Update () method

When AWT receives an applet re-painting request, it calls the update () method of the applet. By default, the update () method clears the background of the applet and then calls the paint () method. Reload the update () method to include the drawing code in the previous paint () method in the update () method to avoid clearing the entire area during each re-painting. Since the background is no longer automatically cleared, Java Programmers need to complete it themselves in update.

Dual-buffer technology

Another way to eliminate the flickering between frames is to use dual-buffering technology, which is used in many animated applets. The main principle is to create a background image, draw each frame into the image, and then call the drawimage () method to draw the entire background image to the screen once. The advantage of this method is that most of the painting is off-screen. Painting an off-screen image at one time is much more effective than painting it directly on the screen. Before creating a background image, you must first call the createimage () method to generate an appropriate background buffer, and then obtain the graph Creation environment (graphics class Object) in the buffer zone ).

The following instance program code ("C2" Code) is the combination of the two methods. The dual Buffer technology is implemented in the update () method of heavy load. Among them, offimage is the image Class Object, offgraphics is the graphics class object, these two class objects are the key to implementing the dual-buffer technology. The related code is as follows:

Public void paint (Graphics g) {Update (g);} public void Update (Graphics g) {dimension D = getsize (); // if the background image does not exist, create a background image if (offgraphics = NULL) | (D. width! = Offdimension. width) | (D. height! = Offdimension. height) {offdimension = D; offimage = createimage (D. width, D. height); offgraphics = offimage. getgraphics ();} // erase the previous offgraphics frame. setcolor (getbackground (); offgraphics. fillrect (0, 0, D. width, D. height); offgraphics. setcolor (color. black); // output the current frame to the specified image for (INT I = 0; I <10; I ++) {offgraphics. drawimage (images [I], framenumber * 5% (D. width/2), I * D. height/10, this);} // output the specified background image G. drawimage (offimage, framenumber * 5% (D. width/2), 0, this );}

The dual-buffering technology can smooth the animation, but there is one drawback: allocate a buffer for the background image. If the image is large, it will occupy a large amount of memory.

 

Gradually improving image tracking and procedures

Image tracking

When the animation thread was just started, because not all the images were loaded, the images displayed on the screen were often incomplete. In this case, you can use mediatracker or imageoberver objects for image tracking. After all the images are loaded, call the drawimage () method to output the images to the screen. The fourth parameter of the drawimage () method is the imageobserver Class Object. Therefore, you can use the imageobserver Class Object for image tracking. Image tracking is implemented in the init () method of the applet, which is equivalent to drawing an image before the drawimage () method of the animation thread is called. Because of the initialization process of the animation thread, that is, the init () method is called first. The following code ("C3" code) demonstrates how the init () method uses mediatracker class objects to load tracking images. The Code is as follows:

Public void Init () {tracker = new midiatracker (this); For (INT I = 1; I <= 10; I ++) {image [I-1] = getimage (getcodebase (), "image" + I + ". GIF "); // use the addimage () method of the mediatracker class object to track image loading. addimage (images [I-1], 0 );}......}

Further Program Improvement

Add the following if statement to the reload Update () method of the "C2" code to determine the image tracking method of the mediatracker class object. The if statement is as follows:

If (! Tracker. checkall () {// if the image has not been loaded, only the background is cleared and a status g is output. clearrect (0, 0, D. width, D. height); G. drawstring ("Please wait... ", 0, D. height/2); return ;}

Add two lines of code to the stop () method of the "C1" code to release the memory resources occupied by the dual-buffer technology. Then, the STOP () method is changed:

Public void stop () {// stop the animation thread animatorthread = NULL; // release the memory resource offgraphics = NULL for double buffering; offimage = NULL ;}

There is also a small problem when the program is modified, that is, after the animation thread is started, the first image may still have traces left, rather than completely erased as the image is updated. To solve this problem, you only need to change the final for () loop and G. drawimage () method in the "C2" code to the following code.

for(int i=0;i<10;i++){  offGraphics.drawImage(images[frameNumber%10],     ,frameNumber*5%(d.width),i*d.height/10,this);}g.drawImage(offImage,0,0,this);

 

Maintain a constant frame speed

In order to make the animation do not flash, at least 12 frames per second are required. A higher frame speed produces smoother animation. Generally, the call thread's sleep () method sleep for a fixed period of time between every two frames of the animation. The disadvantage of doing so is that the absolute delay will lead to a long delay, that is, the waiting time is too long. To display 10 to 10 seconds ~ 20 images with a constant frame speed (that is, a constant display frequency) can be added to the run () method of the animation thread as follows:

try{startTime+=delay;Thread.sleep(Math.max(0,startTime-System.currentTimeMillis()));}catch(InterruptedException e){ break;}

This article focuses on several methods to optimize the Display Effect of Java animation programming. Of course, with the development of Java and other computer technologies, there will also be a variety of methods to optimize the animation display effect, for example, in improving the animation frame speed, you can call Microsoft's DirectDraw tool in Java. However, the methods described in this article are more universal.

 

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.