Question

I'd like to draw a grid. Therefore I've got

private int GRID_WIDTH = 6;  <----Amount of columns
private int GRID_HEIGHT = 6; <----Amount of rows
private int GRID_SIZE; = 50  <----Width and height of a cell

Now I am trying to draw them:

for(int i = 0; i < GRID_WIDTH; i++) {
    for(int j = 0; j < GRID_HEIGHT; j++) {
        canvas.drawRect(new Rect(i*GRID_SIZE + 5, j*GRID_SIZE + 5, GRID_SIZE, GRID_SIZE), paint);
    }
}

The "5" after each coordinate should make a gap between two rectangles. This should end up in some nice grid, but as result I see multiple rectangles pushed together, without these 5px padding between them. No matter what I choose as padding, It resuls in following image: (Here the padding is set to 20 instead of 5...)

enter image description here

What am i doing wrong?

Thanks in advance!

Was it helpful?

Solution

Consider that the Rect constructor signature is:

Rect(int left, int top, int right, int bottom)

and you're doing like:

Rect(int left, int top, int width, int height)

Notice the difference in the last two arguments. You must do like this:

int left = i * (GRID_SIZE + 5);
int top = j * (GRID_SIZE + 5);
int right = left + GRID_SIZE;
int bottom = top + GRID_SIZE;
canvas.drawRect(new Rect(left, top, right, bottom), paint);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top