Daw线穿过画布上的“细胞”

时间:2018-06-05 16:46:21

标签: android grid android-canvas

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

顺便说一下,我有一个带有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)

enter image description here

找不到在每个单元格中绘制其他行的方法,以便将它分成四个部分。

像这样的东西(红色是细胞):

enter image description here

1 个答案:

答案 0 :(得分:2)

//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);
    }
}

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