Game Development Reference
In-Depth Information
Image Update Handler
The image update handler receives an array of ARGB packed pixels representing a color
(see Listing 5-7). It fires multiple times per second, and its job is to replace pixels in the
bitmap with the colors in the array by calling the following method:
mBitmap.setPixels(pixels, offset, stride, x, y, width, height)
The arguments are as follows:
pixels
is the colors to write to the bitmap.
offset
is the index of the first color to read from
pixels[]
.
stride
is the number of colors in
pixels[]
to skip between rows
(normally, this value will be the same as the width of the bitmap).
x
is the x coordinate of the first pixel to write to in the bitmap.
y
is the y coordinate of the first pixel to write to in the bitmap.
width
is the number of colors to copy from
pixels[]
per row.
height
is the number of rows to write to the bitmap.
Listing 5-7. Image Update Handler
public void OnImageUpdate(int[] pixels) {
mBitmap.setPixels(pixels, 0, mWidth, 0, 0, mWidth, mHeight);
mHandler.post(new Runnable() {
public void run() {
mView.setImageBitmap( mBitmap);
}
});
}
Note that because this handler fires from a non-UI thread, you cannot set the pixels directly
into the
ImageView
but must use an
android.os.Handler
to post a
Runnable
to the message
queue, like so:
Handler.post(new Runnable() {
public void run() {
// Code that updates the UI goes here
}
});
Note
A handler allows you to send and process message and runnable objects associated with a
thread's message queue. Each handler instance is associated with a single thread and that thread's
message queue. When you create a new handler, it is bound to the thread and message queue of
the thread that is creating it. Always use a handler when updating UI widgets from a non-UI thread!