Game Development Reference
In-Depth Information
import
android.view.View;
import
android.view.Window;
import
android.view.WindowManager;
public class
RenderViewTest
extends
Activity {
class
RenderView
extends
View {
Random rand =
new
Random();
public
RenderView(Context context) {
super
(context);
}
protected void
onDraw(Canvas canvas) {
canvas.drawRGB(rand.nextInt(256), rand.nextInt(256),
rand.nextInt(256));
invalidate();
}
}
@Override
public void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
requestWindowFeature(Window.
FEATURE_NO_TITLE
);
getWindow().setFlags(WindowManager.LayoutParams.
FLAG_FULLSCREEN
,
WindowManager.LayoutParams.
FLAG_FULLSCREEN
);
setContentView(
new
RenderView(
this
));
}
}
For our first graphics demo, this is pretty concise. We define the
RenderView
class as an inner class
of the
RenderViewTest
activity. The
RenderView
class derives from the
View
class, as discussed
earlier, and has a mandatory constructor as well as the overridden
onDraw()
method. It also has an
instance of the
Random
class as a member; we'll use that to generate our random colors.
The
onDraw()
method is dead simple. We first tell the
Canvas
to fill the whole view with a random
color. For each color component, we simply specify a random number between 0 and 255
(
Random.nextInt()
is exclusive). After that, we tell the system that we want the
onDraw()
method
to be called again as soon as possible.
The
onCreate()
method of the activity enables full-screen mode and sets an instance of our
RenderView
class as the content view. To keep the example short, we're leaving out the wake
lock for now.
Taking a screenshot of this example is a little bit pointless. All it does is fill the screen with a
random color as fast as the system allows on the UI thread. It's nothing to write home about.
Let's do something more interesting instead: draw some shapes.
Note
The preceding method of continuous rendering works, but we strongly recommend not
using it! We should do as little work on the UI thread as possible. In a minute, we'll use a separate
thread to discuss how to do it properly, where later on we can also implement our game logic.