Reputation: 61
I would like for this to display as a 7 x 7 square grid in the centre of the screen, however as you can see with my current code the vertical lines are in the correct positions but the horizontal ones are not. I am sure this is a simple fix and any help would be appreciated -
public class GameGrid extends View {
Paint black = new Paint();
public GameGrid(Context context) {
super(context);
black.setColor(Color.BLACK);
black.setStrokeWidth(8);
}
@Override
public void onDraw(Canvas canvas) {
float startX;
float stopX;
float startY;
float stopY;
int width = canvas.getWidth();
int height = canvas.getHeight();
int gridSize = 7;
int gridSpacing = width / gridSize;
//Vertical Grid-lines
for (int i = 0; i < gridSize; i++) {
startX = width / 2 - height / 2;
stopX = width / 2 + height / 2;
startY = i*gridSpacing;
stopY = i*gridSpacing;
canvas.drawLine(startX, startY, stopX, stopY, black);
}
//Horizontal Grid-lines
for (int i = 0; i < gridSize; i++) {
startX = i*gridSpacing;
stopX = i*gridSpacing;
startY = height / 2 - width / 2;
stopY = height / 2 + width / 2;
canvas.drawLine(startX, startY, stopX, stopY, black);
}
}
Picture of what grid currently looks like
Upvotes: 3
Views: 1969
Reputation: 1324
I'd GUESS the problem is that the canvas isn't square? Height is greater than width.
Thus in the vertical Gridlines
startX = width / 2 - height / 2;
gives a negative number and puts the starting point to the left off-screen. It looks fine, but the length is wrong.
For the horizontal Gridlines
startY = height / 2 - width / 2;
is a positive number and you start partway down the screen. Similarly, the endY
value overshoots by some amount (note the horizontal gridlines are longer than the vertical gridlines as well as being offset downward)
Perhaps try
//Horizontal Y vals
startY = 0;
stopY = height;
Upvotes: 1
Reputation: 1668
You are missing the offset (on both axis). Why you don't pre-calculate xOffset
and yOffset
and the start to paint based on the point (xOffset, yOffset)
?
something like this:
@Override
public void onDraw(Canvas canvas) {
float startX;
float stopX;
float startY;
float stopY;
int width = canvas.getWidth();
int height = canvas.getHeight();
int gridSize = 7;
int gridSpacing = Math.min(width, height) / gridSize;
int boardSize = gridSize * gridSpacing;
int xOffset = (width - boardSize)/2;
int yOffset = (height - boardSize)/2;
//Vertical Grid-lines
for (int i = 0; i < gridSize; i++) {
startX = xOffset + i*gridSpacing;
startY = yOffset;
stopX = startX;
stopY = startY + boardSize;
canvas.drawLine(startX, startY, stopX, stopY, black);
}
//Horizontal Grid-lines
for (int i = 0; i < gridSize; i++) {
startX = xOffset;
startY = yOffset + i*gridSpacing;
stopX = startX + boardSize;
stopY = startY;
canvas.drawLine(startX, startY, stopX, stopY, black);
}
}
If you want to make sure that will be always centered (e.g. in landscape ) you should set:
int gridSpacing = Math.min(width, height) / gridSize;
Upvotes: 5