为Android游戏绘制方形网格时遇到问题

JCH*_*530 3 java grid android android-studio

我希望它在屏幕中央显示为 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

网格当前的样子的图片 在此处输入图片说明

leo*_*rdo 5

您缺少偏移量(在两个轴上)。为什么你不预先计算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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想确保始终居中(例如在 Landscape 中),您应该设置:

int gridSpacing = Math.min(width, height) / gridSize;
Run Code Online (Sandbox Code Playgroud)