Game Development Reference
In-Depth Information
Continuous Rendering in the UI Thread
All we've done up until now is set the text of a
TextView
when needed. The actual rendering has
been performed by the
TextView
itself. Let's create our own custom
View
whose sole purpose
is to let us draw stuff to the screen. We also want it to redraw itself as often as possible, and we
want a simple way to perform our own drawing in that mysterious redraw method.
Although this may sound complicated, in reality Android makes it really easy for us to create
such a thing. All we have to do is create a class that derives from the
View
class, and override a
method called
View.onDraw()
. This method is called by the Android system every time it needs
our
View
to redraw itself. Here's what that could look like:
class
RenderView
extends
View {
public
RenderView(Context context) {
super
(context);
}
protected void
onDraw(Canvas canvas) {
// to be implemented
}
}
Not exactly rocket science, is it? We get an instance of a class called
Canvas
passed to the
onDraw()
method. This will be our workhorse in the following sections. It lets us draw shapes
and bitmaps to either another bitmap or a
View
(or a
Surface
, which we'll talk about in a bit).
We can use this
RenderView
as we'd use a
TextView
. We just set it as the content view of our
activity and hook up any input listeners we need. However, it's not all that useful yet, for two
reasons: it doesn't actually draw anything, and even if it were able to draw something, it would
only do so when the activity needed to be redrawn (that is, when it is created or resumed, or
when a dialog that overlaps it becomes invisible). How can we make it redraw itself?
Easy, like this:
protected
void
onDraw(Canvas canvas) {
// all drawing goes here
invalidate();
}
The call to the
View.invalidate()
method at the end of
onDraw()
will tell the Android system to
redraw the
RenderView
as soon as it finds time to do that again. All of this still happens on the
UI thread, which is a bit of a lazy horse. However, we actually have continuous rendering with
the
onDraw()
method, albeit relatively slow continuous rendering. We'll fix that later; for now, it
suffices for our needs.
So, let's get back to the mysterious
Canvas
class. It is a pretty powerful class that wraps a
custom low-level graphics library called Skia, specifically tailored to perform 2D rendering on the
CPU. The
Canvas
class provides us with many drawing methods for various shapes, bitmaps,
and even text.
Where do the draw methods draw to? That depends. A
Canvas
can render to a
Bitmap
instance;
Bitmap
is another class provided by the Android's 2D API, which we'll look into later in this