1

I am trying to draw a grid for a game but my lines are offset from where I want them. I have tried adding a fixed offset but I want it to be scaleable on difference devices.

Here is the code for creating the path the View will draw:

    float top = getPaddingTop() + getTop();
    float bot = getBottom() - getPaddingBottom();
    float left = getLeft() + getPaddingLeft();
    float right = getRight() - getPaddingRight();
    float squareWidth = (right - left) / 10;
    float squareHeight = (bot - top) / 10;

    gridPath.moveTo(left, top);
    gridPath.lineTo(left, bot);
    gridPath.lineTo(right, bot);
    gridPath.lineTo(right, top);

    gridPath.close();

    for (int i = 1; i < 10; i++) {
        gridPath.moveTo(squareWidth * i, top);
        gridPath.lineTo(squareWidth * i, bot);
    }

    for (int i = 1; i < 10; i++){
        gridPath.moveTo(left, squareHeight * i);
        gridPath.lineTo(right, squareHeight * i);
    }

    gridPath.close();

I want an evenly drawn grid but I get this:enter image description here

Is there something I am missing?

J Blaz
  • 783
  • 1
  • 6
  • 26

1 Answers1

1

You're not accounting for the left and top paddings in your for loops:

for (int i = 1; i < 10; i++) {
    gridPath.moveTo(getPaddingLeft() + squareWidth * i, top);
    gridPath.lineTo(getPaddingLeft + squareWidth * i, bot);
}

for (int i = 1; i < 10; i++){
    gridPath.moveTo(left, getPaddingTop() + squareHeight * i);
    gridPath.lineTo(right, getPaddingTop() + squareHeight * i);
}   

Also, the getLeft(), getRight(), getTop(), getBottom() methods are relative to the View's position in its parent, so your initializations are going to cause problems if the View doesn't happen to fill its parent. The following is probably preferable:

float top = getPaddingTop();
float bot = getHeight() - getPaddingBottom();
float left = getPaddingLeft();
float right = getWidth() - getPaddingRight();
Mike M.
  • 38,532
  • 8
  • 99
  • 95
  • But I am when I calculate squareWidth I need to do it again? – J Blaz Oct 24 '15 at 23:02
  • Yes, because that's just to do with the square's width, not its x-coordinate offset. – Mike M. Oct 24 '15 at 23:05
  • 1
    Thank you very much! I thought I had it taken care of but it needs to be added again because of what you said. Thank you! – J Blaz Oct 24 '15 at 23:09
  • @JBlaz I shoulda mentioned earlier, but you might consider using `Canvas#drawLine()` methods instead using of a `Path` for your grid. It's generally faster. – Mike M. Oct 25 '15 at 08:27
  • Okay thank you! Do you mean it is faster like it draws to the screen faster and makes the app more responsive? – J Blaz Oct 26 '15 at 23:21
  • 1
    Yeah, it draws faster. You might have a look at [this answer](http://stackoverflow.com/a/15208783) from Romain Guy, an engineer at Google, for a little explanation. – Mike M. Oct 26 '15 at 23:26