我希望在屏幕中央显示为7 x 7方格,但是正如您在当前代码中看到的那样,垂直线位于正确的位置,而水平线则不是。我相信这是一个简单的解决方案,任何帮助将不胜感激 -
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);
}
}
答案 0 :(得分:3)
您缺少偏移(在两个轴上)。为什么不预先计算xOffset
和yOffset
以及根据(xOffset, yOffset)
点开始绘画?
类似的东西:
@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);
}
}
如果您想确保始终居中(例如在风景中),您应该设置:
int gridSpacing = Math.min(width, height) / gridSize;
答案 1 :(得分:1)
我是GUESS问题是画布不是正方形的吗?高度大于宽度。
因此在垂直网格线中
startX = width / 2 - height / 2;
给出一个负数,并将起点放在屏幕左侧。它看起来很好,但长度是错误的。
对于水平网格线
startY = height / 2 - width / 2;
是一个正数,你从屏幕中间开始。同样,endY
值超过一定量(注意水平网格线比垂直网格线长,并向下偏移)
也许试试
//Horizontal Y vals
startY = 0;
stopY = height;