Game Development Reference
In-Depth Information
Drawing Lines
To draw a line, we can use the following
Canvas
method:
Canvas.drawLine(float startX, float startY, float stopX, float stopY, Paint paint);
The first two arguments specify the coordinates of the starting point of the line, the next two
arguments specify the coordinates of the endpoint of the line, and the last argument specifies a
Paint
instance. The line that gets drawn will be one pixel thick. If we want the line to be thicker,
we can specify its thickness in pixels by setting the stroke width of the
Paint
instance:
Paint.setStrokeWidth(float widthInPixels);
Drawing Rectangles
We can also draw rectangles with the following
Canvas
method:
Canvas.drawRect(float topleftX, float topleftY, float bottomRightX, float bottomRightY,
Paint paint);
The first two arguments specify the coordinates of the top-left corner of the rectangle, the next
two arguments specify the coordinates of the bottom-left corner of the rectangle, and the
Paint
specifies the color and style of the rectangle. So what style can we have and how do we set it?
To set the style of a
Paint
instance, we call the following method:
Paint.setStyle(Style style);
Style
is an enumeration that has the values
Style.FILL
,
Style.STROKE
, and
Style.FILL_AND_
STROKE
. If we specify
Style.FILL
, the rectangle will be filled with the color of the
Paint
. If we
specify
Style.STROKE
, only the outline of the rectangle will be drawn, again with the color and
stroke width of the
Paint
. If
Style.FILL_AND_STROKE
is set, the rectangle will be filled, and the
outline will be drawn with the given color and stroke width.
Drawing Circles
More fun can be had by drawing circles, either filled or stroked (or both):
Canvas.drawCircle(float centerX, float centerY, float radius, Paint paint);
The first two arguments specify the coordinates of the center of the circle, the next argument
specifies the radius in pixels, and the last argument is again a
Paint
instance. As with the
Canvas.drawRectangle()
method, the color and style of the
Paint
will be used to draw the circle.
Blending
One last thing of importance is that all of these drawing methods will perform alpha blending.
Just specify the alpha of the color as something other than 255 (0xff), and your pixels, lines,
rectangles, and circles will be translucent.