Game Development Reference
In-Depth Information
chapter. In this case, it is drawing to the area on the screen that the
View
is taking up. Of course,
this is an insane oversimplification. Under the hood, it will not draw directly to the screen, but
rather to some sort of bitmap that the system will later use in combination with the bitmaps of all
other
View
s of the activity to composite the final output image. That image will then be handed
over to the GPU, which will display it on the screen through another set of mysterious paths.
We don't really need to care about the details. From our perspective, our
View
seems to stretch
over the whole screen, so it may as well be drawing to the framebuffer of the system. For the
rest of this discussion, we'll pretend that we directly draw to the framebuffer, with the system
doing all the nifty things like vertical retrace and double-buffering for us.
The
onDraw()
method will be called as often as the system permits. For us, it is very similar
to the body of our theoretical game main loop. If we were to implement a game with this
method, we'd place all our game logic into this method. We won't do that for various reasons,
performance being one of them.
So let's do something interesting. Every time you get access to a new drawing API, write a little
test that checks if the screen is really redrawn frequently. It's sort of a poor man's light show. All
you need to do in each call to the redraw method is to fill the screen with a new random color.
That way you only need to find the method of that API that allows you to fill the screen, without
needing to know a lot about the nitty-gritty details. Let's write such a test with our own custom
RenderView
implementation.
The method of the
Canvas
to fill its rendering target with a specific color is called
Canvas.drawRGB()
:
Canvas.drawRGB(int r, int g, int b);
The
r
,
g
, and
b
arguments each stand for one component of the color that we will use to fill
the “screen.� Each of them has to be in the range 0 to 255, so we actually specify a color in
the RGB888 format here. If you don't remember the details regarding colors, take a look at the
“Encoding Colors Digitally� section of Chapter 3 again, as we'll be using that info throughout the
rest of this chapter.
Listing 4-12 shows the code for our little light show.
Caution
Running this code will rapidly fill the screen with a random color. If you have epilepsy or
are otherwise light-sensitive in any way, don't run it.
Listing 4-12. The RenderViewTest Activity
package
com.badlogic.androidgames;
import
java.util.Random;
import
android.app.Activity;
import
android.content.Context;
import
android.graphics.Canvas;
import
android.os.Bundle;