绘制网格偏移

Drawn Grid Offset

我正在尝试为游戏绘制网格,但我的线条偏离了我想要的位置。我试过添加一个固定的偏移量,但我希望它可以在不同的设备上缩放。

下面是创建视图绘制路径的代码:

    float top = getPaddingTop() + getTop();
    float bot = getBottom() - getPaddingBottom();
    float left = getLeft() + getPaddingLeft();
    float right = getRight() - getPaddingRight();
    float squareWidth = (right - left) / 10;
    float squareHeight = (bot - top) / 10;

    gridPath.moveTo(left, top);
    gridPath.lineTo(left, bot);
    gridPath.lineTo(right, bot);
    gridPath.lineTo(right, top);

    gridPath.close();

    for (int i = 1; i < 10; i++) {
        gridPath.moveTo(squareWidth * i, top);
        gridPath.lineTo(squareWidth * i, bot);
    }

    for (int i = 1; i < 10; i++){
        gridPath.moveTo(left, squareHeight * i);
        gridPath.lineTo(right, squareHeight * i);
    }

    gridPath.close();

我想要一个均匀绘制的网格,但我明白了:

有什么我遗漏的吗?

您没有考虑 for 循环中的左侧和顶部填充:

for (int i = 1; i < 10; i++) {
    gridPath.moveTo(getPaddingLeft() + squareWidth * i, top);
    gridPath.lineTo(getPaddingLeft + squareWidth * i, bot);
}

for (int i = 1; i < 10; i++){
    gridPath.moveTo(left, getPaddingTop() + squareHeight * i);
    gridPath.lineTo(right, getPaddingTop() + squareHeight * i);
}   

此外,getLeft()getRight()getTop()getBottom() 方法是相对于 View 在其父项中的位置的,因此您的如果 View 没有恰好填充其父项,初始化将导致问题。以下可能更可取:

float top = getPaddingTop();
float bot = getHeight() - getPaddingBottom();
float left = getPaddingLeft();
float right = getWidth() - getPaddingRight();