首页 > 解决方案 > Daw 线穿过画布上的“细胞”

问题描述

我需要弄清楚如何绘制通过单元格中心的垂直和水平线。

顺便说一句,我有一个包含 100x100 单元格的 2D 网格,我如何绘制通过这些单元格内部的线,将每个单元格分成 4 部分?

我用波纹管来画:

//Draw grid lines horizontally and vertically
    for (int i = 0; i < gameBoard.length; i++) {
        if((i * cellWidth) + xOffset > 0 && (i * cellWidth) + xOffset < width) {
            canvas.drawLine((i * cellWidth) + xOffset, 0, (i * cellWidth) + xOffset, height, blackPaint);
        }
    }

    for (int i = 0; i < gameBoard[0].length; i++) {
        if((i * cellHeight) + yOffset > 0 && (i * cellHeight) + yOffset < height) {
            canvas.drawLine(0, (i * cellHeight) + yOffset, width, (i * cellHeight) + yOffset, blackPaint);
        }
    }

这画了一些与此类似的东西(每个单元格都有一个 GestureDetector)

在此处输入图像描述

无法找到一种方法在每个单元格内绘制这次经过的其他线条,以便将其分为四个部分。

像这样的东西(红色是单元格):

在此处输入图像描述

标签: androidgridandroid-canvas

解决方案


//Draw grid lines horizontally and vertically
for (int i = 0; i < gameBoard.length; i++) {
    if((i * cellWidth) + xOffset > 0 && (i * cellWidth) + xOffset < width) {
        canvas.drawLine((i * cellWidth) + xOffset, 0, (i * cellWidth) + xOffset, height, blackPaint);
    }
}

for (int i = 0; i < gameBoard[0].length; i++) {
    if((i * cellHeight) + yOffset > 0 && (i * cellHeight) + yOffset < height) {
        canvas.drawLine(0, (i * cellHeight) + yOffset, width, (i * cellHeight) + yOffset, blackPaint);
    }
}

xOffset += cellWidth * 0.5f;
yOffset += cellHeight * 0.5f;

//Draw grid lines horizontally and vertically AGAIN.. but now with offsets moved half size to the right/bottom
for (int i = 0; i < gameBoard.length; i++) {
    if((i * cellWidth) + xOffset > 0 && (i * cellWidth) + xOffset < width) {
        canvas.drawLine((i * cellWidth) + xOffset, 0, (i * cellWidth) + xOffset, height, blackPaint);
    }
}

for (int i = 0; i < gameBoard[0].length; i++) {
    if((i * cellHeight) + yOffset > 0 && (i * cellHeight) + yOffset < height) {
        canvas.drawLine(0, (i * cellHeight) + yOffset, width, (i * cellHeight) + yOffset, blackPaint);
    }
}

作为旁注,我会考虑使用函数而不是重复代码!祝你好运 ;)


推荐阅读