如何从网格位置计算行/列?

16

假设我有一个网格,我知道它的行数(固定数量),并且我知道当前列数的计数(可以任意增加),如何从其索引计算出方块所在的行和列?

           +   +   +   +   +
 Cols ---> | 0 | 1 | 2 | 3 | ...
        +--+---|---|---|---|---
         0 | 0 | 3 | 6 | 9 | ...
        +--+---|---|---|---|---
 Rows    1 | 1 | 4 | 7 | A | ...
        +--+---|---|---|---|---
         2 | 2 | 5 | 8 | B | ...
        +--+---|---|---|---|---
         .   .   .   .   .   ...
         .   .   .   .   .   .
         .   .   .   .   .   .

因此,假设给定:

final int mRowCount = /* something */;
int mColCount;

并且给定一个函数:

private void func(int index) {

    int row = index % mRowCount;
    int col = ???

我应该如何正确计算col?我相信它必须是列数和行数的函数,但我的思维不够清晰。

示例:如果index == 4,则row=1col=1。如果index == 2,则row=2col=0

谢谢。

7个回答

8

我不太理解你的设置,但如果你有一个普通的网格,带有像Android GridLayout中那样的渐进索引:

 +-------------------+
 | 0 | 1 | 2 | 3 | 4 |
 |---|---|---|---|---|
 | 5 | 6 | 7 | 8 | 9 | 
 |---|---|---|---|---|
 | 10| 11| 12| 13| 14|
 |---|---|---|---|---|
 | 15| 16| 17| 18| 19| 
 +-------------------+

计算方法如下:
int col = index % colCount;
int row = index / colCount;

例如:

row of index 6 = 6 / 5 = 1
column of index 12 = 12 % 5 = 2

好的,现在,如果我想要分页怎么办?比如说我想每页最多显示3行。因此对于上面的例子,第1页将显示行1, 2, 3,而第2页将显示行4。我希望int row = ....公式能够返回15..19中的行号为1 - tig

7

int col = index / mRowCount;


6

index = col * mRowCount + row

然后

row = index % mRowCount;

col = index / mRowCount;


4

我认为该列将通过整数除法获得:

int col = index / mRowCount;

通过使用乘法和减法来替换取模运算,可以将其限制在单个部分中。我不确定这是否更具成本效益; 在大多数情况下可能并不重要:

int col = index / mRowCount;
int row = index - col * mRowCount;

1
row = CEILING(index / numberOfColumns)    

CEILING将数字向上舍入到下一个整数

col = MOD(index / numberOfColumns)

除了一种情况,您必须考虑——> 当MOD=0时,当列结果为ZERO时,您将设置col = numberOfColumns (例如,假设numberOfColumns = 48…那么,MOD(96,48)为ZERO,MOD(48,48)= 0也是如此…因为任何可被48整除的数都将是MOD = 0…换句话说,当MOD = 0时,您在最后或最高列,您在numberOfColumns列中


0
column = index / max_rows;
row    = index % max_rows;

0

行 = 索引 / 列数

以及

列 = 索引 % 列数


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接