Java animation programming foundation second part

zhaozj2021-02-08  443

Draw each frame:

The rest is to draw each frame image. The replet repain is called in the above example.

To draw each frame image.

Public void paint (graphics g) {

g.setcolor (color.ble);

g.drawstring ("Frame" Frame, 0, 30);

}

Generate graphics:

Now let's draw some slightly difficult things. The next example draws a combination of sinusoidal curve,

For each X, draw a short vertical line, all of these lines constitute a graphic, and each frame changes.

But unfortunate some flashing, after we will explain why flashes and how to avoid it.

Public void paint (graphics g) {

Dimension D = Size ();

INT H = D.height / 2;

For (int x = 0; x

INT Y1 = (int) ((1.0 math.sin (x - frame) * 0.05)) * h);

INT Y2 = (INT) ((1.0 math.sin ((x frame) * 0.05) * h);

g.drawline (x, y1, x, y2);

}

}

Avoid flashing:

There are two reasons in the flash in the above example: drawing each frame too long (because of the redraw

The amount of calculation is larger), and the other is cleared at each background, and when the next frame is performed.

When calculating, the user sees the background.

The short time to clear the background and draw the graph is being seen by the user, it is flashing. In some platforms

If the PC flash is obvious than in X WINDOW, this is because the image of x window is cached, making it blinking

The time is short.

There are two ways to significantly lose glitter: overload Update () or use double buffer.

Reserved UPDATE ()?

When the AWT receives an applet's redraw request, it calls the applet's update ().

By default, update () clears the background of the applet and calls Paint (). Heavy daily update (), will

The drawing code in the Paint () is included in Update (), thereby avoiding the entire area each time.

Clear.

Since the background is not automatically cleared, we need to complete it in Update (). We are drawing

The vertical line is erased alone before the new line, completely eliminated the flash.

Public void paint (graphics g) {

Update (g);

}

Public void Update (graphics g) {

Color bg = getBackground ();

Dimension D = Size ();

INT H = D.height / 2;

For (int x = 0; x

INT Y1 = (int) ((1.0 math.sin (x - frame) * 0.05)) * h);

INT Y2 = (INT) ((1.0 math.sin ((x frame) * 0.05) * h);

IF (Y1> Y2) {

INT T = Y1;

Y1 = Y2;

Y2 = T;

}

G.SetColor (BG);

g.drawline (x, 0, x, y1);

g.drawline (x, y2, x, d.height);

g.setcolor (color.ble);

g.drawline (x, y1, x, y2);

}

}

转载请注明原文地址:https://www.9cbs.com/read-902.html

New Post(0)