user1953208
user1953208

Reputation: 169

How to scale a square grid to any phone's dimensions

Hi I'm trying to make a square 8x8 grid on a canvas. I've managed to make a grid, but it turns out to be rectangular, but for the game I'm making it needs to be square. How do I change my code to make it a square grid scaled to the phone.

float testWidth = (getWidth() - 16f) / 9f;
float testHeight = (getHeight() - 16f) / 9f;
for (int i = 0; i < 9; i++) {
            canvas.drawLine(padding + testWidth* i, padding, padding
                    + testWidth * i, testHeight* 8+padding, dark);
            canvas.drawLine(padding,  padding+testHeight* i, testWidth* 8
                    + padding, padding+testHeight* i, dark);
        }

EDIT: I can now make a square grid, but I don't know how to center the grid into the middle of the phone

Upvotes: 3

Views: 267

Answers (1)

Blenderer
Blenderer

Reputation: 702

You'll want to take the shortest of the two (Width or Height) and use that to build the grid upon. (So your grid can fit on the screen)

Something like...:

float gridSide = 0;
if (getWidth() > getHeight()) {
  gridSide = getHeight();
}
else {
  gridSide = getWidth();
}

Simpler logic provided by appsroxcom:

float gridSide = Math.min(testWidth(), testHeight());

Use gridSide as the total length and total width of the grid

Upvotes: 4

Related Questions