user1953208
user1953208

Reputation: 169

game grid will not scale appropriately for different phones on android

I'm creating a grid for my game, but I want the size of the grid to vary, depending on the phone's dimensions. When I run the code (note: I removed a lot from ondraw, only concerned about lines atm), it seems like the size of the grid is the same on both my HTC Desire and Wildfire - Which makes the grid look perfect on the wildfire, but there is a massive space below the grid on the desire- prob cos the desire screen is bigger? What I'm asking is...

How do i make the grid scale to the phones dimensions - I want the grid to take up the majority of the phone's screen, but have a margin.Thanks

   protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        padding = 8;
        for (int i = 0; i < 9; i++) {
            canvas.drawLine(padding + testWidth* i, padding, padding
                    + testWidth * i, testWidth* 8+padding, dark);
            canvas.drawLine(padding,  padding+testWidth* i, testWidth* 8
                    + padding, padding+testWidth* i, dark);
        }
    }

}
    public void onSizeChanged(int w, int h, int oldw, int oldh) {
        testWidth= w / 9f;
        testHeight = h / 9f;
        border = w;
        getRect(selX, selY, selRect);
        super.onSizeChanged(w, h, oldw, oldh);

    }

EDIT: I can now make a grid that scales to the phone's dimensions, however it is a rectangular grid. It looks kind of silly, I need a square one. Maybe I should make padding bigger if the screen is bigger?

Upvotes: 2

Views: 183

Answers (2)

Anuraag
Anuraag

Reputation: 76

This answer is supplementing Nicolas Brown's answer, but you might identify your problem a little better by introducing some more local variables. For example, your original loop could be replaced by:

padding = 8;
for (int i = 0; i < 9; i++) {
    int xposition = padding + testWidth * i;
    int yposition = padding + testHeight * i;
    // Horizontal line
    canvas.drawLine(padding, yposition, padding + testWidth * 8, yposition, dark);
    // Vertical line
    canvas.drawLine(xposition, padding, xposition, padding + testHeight * 8, dark);
}

Also, as Nicolas suggested, you are not accounting for the 8 pixel padding. So, in your onSizeChanged you want:

testWidth = (w - 16f) / 9f;
testHeight = (h - 16f) / 9f;

Upvotes: 1

Nicolas Brown
Nicolas Brown

Reputation: 1574

The problem is a typing error. Seems like you've copied and pasted testWidth and forgot to change it to. Try this:

protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        padding = 8;
        for (int i = 0; i < 9; i++) {
            canvas.drawLine(padding + testWidth* i, padding, padding
                    + testWidth * i, testWidth* 8+padding, dark);
            canvas.drawLine(padding,  padding+testHeight* i, testHeight* 8
                    + padding, padding+testHeight* i, dark);
        }
    }

Upvotes: 0

Related Questions