The first thing we want to know 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 the 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 actually 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, there are only two things we are interested in: 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 like Color.RED, Color.YELLOW, and so on. You can use these if you don't want to specify a hexadecimal value yourself.
Was this article helpful?