我正在尝试为游戏画一个网格,但我的线条偏离了我想要的位置。我尝试添加一个固定的偏移量,但我希望它可以在不同的设备上进行扩展。
以下是创建View将绘制的路径的代码:
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();
我有什么遗失的吗?
答案 0 :(得分:1)
您未考虑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();