0

I am currently trying to create a grid of multiple squares (Should be a minesweeper grid one day).

Now my solution of getting every mine a specific position is by using this loop:

for(int i = 0; i < cols; i++) 
{
    for(int j = 0; j < rows; j++) 
    {
        mines[i][j].setCoordinates(xCounter, yCounter);
        xCounter+=150; 
    }
    yCounter+=150;
    xCounter = 0;
}

now 150 should display the width or the height of one square because if one mine is on (0,0) the next should be on (minewidth,0) to fit nice and snuggly.

But now my question is, how can I be independend of this 150?

I got to this number by trying out which number makes the grid without spacing. But when I use a lower density device the images are smaller but the distance to each other would remain 150 pixels.

Now how can I get something generally to be independent of this constant?

First I thought I could use the .getWidth() method to get the width of the Bitmap that is stored in my "Mine" class. But this didn't work out so...

Has anyone got an idea to create a grid independent of which density the device has?

tshepang
  • 12,111
  • 21
  • 91
  • 136

1 Answers1

0

You can try to get the width and height of your screen(in dp) and use a factor to determine the width for each grid..

You can add the below code in your application class,

DisplayMetrics displayMetrics = applicationContext.getResources().getDisplayMetrics();
int absoluteWidthPx = displayMetrics.widthInPixels;
int abduluteHeightPx = displayMetrics.heightInPixels;

float scalingFactor = displayMetrics.density;

Now you can find the dp values for width and height of the screen,

/** pixels = densityIndependantPixels * (dotsPerInch/160), based on this **/
int dpWidth = (int)(absoluteWidthPx /scalingFactor);
int dpHeight = (int)(abduluteHeightPx /scalingFactor);

Once you have the width and height in dp you can try using some factors to determine the width for each grid.

deepdroid
  • 633
  • 5
  • 26