Rendering Inside onDraw(Canvas)
Listing 31.9 Overriding onDraw(Canvas) (BoxDrawingView.java)
public BoxDrawingView(Context context, AttributeSet attrs) {
...
}
@Override
protected void onDraw(Canvas canvas) {
// Fill the background
canvas.drawPaint(mBackgroundPaint);
for (Box box : mBoxen) {
float left = Math.min(box.getOrigin().x, box.getCurrent().x);
float right = Math.max(box.getOrigin().x, box.getCurrent().x);
float top = Math.min(box.getOrigin().y, box.getCurrent().y);
float bottom = Math.max(box.getOrigin().y, box.getCurrent().y);
canvas.drawRect(left, top, right, bottom, mBoxPaint);
}
}
The first part of this code is straightforward: Using your off-white background paint, you fill the canvas
with a backdrop for your boxes.
Then, for each box in your list of boxes, you determine what the left, right, top, and bottom of the box
should be by looking at the two points for the box. The left and top values will be the minimum values,
and the bottom and right will be the maximum values.
After calculating these values, you call Canvas.drawRect(...) to draw a red rectangle onto the screen.
Run DragAndDraw and draw some red rectangles (Figure 31.5).
Figure 31.5 An expression of programmerly emotion