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. But since our View spans the complete screen, we can pretend it does. In order to know where we can render our game elements to, we need to know how many pixels there are on the x-axis and on the 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 the Canvas renders to. Note that, depending on what orientation our activity has, the width might be smaller or larger than the height. My Nexus One, for example, has a resolution of 480x800 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 how the coordinate system we render to is organized. 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, be it in portrait or 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 48x32 pixels, in landscape mode.

Figure 4-12. The coordinate system of a 48x32-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 you a hypothetical screen coordinate system in landscape mode. By now you should be able to image how the coordinate system would look in portrait mode.

All the drawing methods of Canvas operate within such a coordinate system. Usually we can address a lot more pixels than in our 48x32-pixel example (e.g., 800x480). That said, let's finally draw some pixels, lines, circles, and rectangles.

NOTE: You may have noticed that different devices can have difference screen resolutions. We'll look into that problem in the next chapter. For now let's just concentrate on finally getting something on the screen ourselves.

+2 -2

Post a comment