Game Development Reference
In-Depth Information
All of the drawing methods of Canvas operate within this type of coordinate system. Usually, we
can address many more pixels than we can in our 48×32-pixel example (e.g., 800×480). That
said, let's finally draw some pixels, lines, circles, and rectangles.
Note You may have noticed that different devices can have different 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.
Drawing Simple Shapes
Deep into Chapter 4, and we are finally on our way to drawing our first pixel. We'll quickly go
over some of the drawing methods provided to us by the Canvas class.
Drawing Pixels
The first thing we want to tackle is how to draw a single pixel. That's done with the following
method:
Canvas.drawPoint(float x, float y, Paint paint);
Two things to notice immediately are that the coordinates of the pixel are specified with floats,
and that Canvas doesn't let us specify the color directly, but instead wants an instance of the
Paint class from us.
Don't get confused by the fact that we specify coordinates as floats. Canvas has some very
advanced functionality that allows us to render to noninteger coordinates, and that's where this
is coming from. We won't need that functionality just yet, though; we'll come back to it in the
next chapter.
The Paint class holds style and color information to be used for drawing shapes, text, and
bitmaps. For drawing shapes, we are interested in only two things: the color the paint holds and
the style. Since a pixel doesn't really have a style, let's concentrate on the color first. Here's how
we instantiate the Paint class and set the color:
Paint paint = new Paint();
paint.setARGB(alpha, red, green, blue);
Instantiating the Paint class is pretty painless. The Paint.setARGB() method should also be
easy to decipher. The arguments each represent one of the color components of the color, in the
range from 0 to 255. We therefore specify an ARGB8888 color here.
Alternatively, we can use the following method to set the color of a Paint instance:
Paint.setColor(0xff00ff00);
We pass a 32-bit integer to this method. It again encodes an ARGB8888 color; in this case, it's
the color green with alpha set to full opacity. The Color class defines some static constants that
encode some standard colors, such as Color.RED , Color.YELLOW , and so on. You can use these if
you don't want to specify a hexadecimal value yourself.
 
Search WWH ::




Custom Search