Game Development Reference
In-Depth Information
Getting the Screen Resolution (and Coordinate Systems)
In Chapter 2, we talked a lot about the framebuffer and its properties. Remember that a
framebuffer holds the colors of the pixels that get displayed on the screen. The number of
pixels available to us is defined by the screen resolution, which is given by its width and height
in pixels.
Now, with our custom View implementation, we don't actually render directly to the framebuffer.
However, since our View spans the complete screen, we can pretend it does. In order to know
where we can render our game elements, we need to know how many pixels there are on the
x axis and y axis, or the width and height of the screen.
The Canvas class has two methods that provide us with that information:
int width = canvas.getWidth();
int height = canvas.getHeight();
This returns the width and height in pixels of the target to which the Canvas renders. Note that,
depending on the orientation of our activity, the width might be smaller or larger than the height.
An HTC Thunderbolt, for example, has a resolution of 480×800 pixels in portrait mode, so the
Canvas.getWidth() method would return 480 and the Canvas.getHeight() method would return
800. In landscape mode, the two values are simply swapped: Canvas.getWidth() would return
800 and Canvas.getHeight() would return 480.
The second piece of information we need to know is the organization of the coordinate system
to which we render. First of all, only integer pixel coordinates make sense (there is a concept
called subpixels, but we will ignore it). We also already know that the origin of that coordinate
system at (0,0) is always at the top-left corner of the display, in both portrait mode and
landscape mode. The positive x axis is always pointing to the right, and the y axis is always
pointing downward. Figure 4-12 shows a hypothetical screen with a resolution of 48×32 pixels,
in landscape mode.
Figure 4-12. The coordinate system of a 48×32-pixel-wide screen
Note how the origin of the coordinate system in Figure 4-12 coincides with the top-left pixel of the
screen. The bottom-left pixel of the screen is thus not at (48,32) as we'd expect, but at (47,31).
In general, (width - 1, height - 1) is always the position of the bottom-right pixel of the screen.
Figure 4-12 shows a hypothetical screen coordinate system in landscape mode. By now you
should be able to imagine how the coordinate system would look in portrait mode.
 
Search WWH ::




Custom Search