gpt4 book ai didi

java - 无法为安卓游戏绘制正方形网格

转载 作者:太空狗 更新时间:2023-10-29 16:29:51 24 4
gpt4 key购买 nike

我希望它在屏幕中央显示为 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);
}
}

Picture of what grid currently looks like enter image description here

最佳答案

您缺少偏移量(在两个轴上)。为什么不预先计算xOffsetyOffset,并根据(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;

关于java - 无法为安卓游戏绘制正方形网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42280172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com