获取整数中的二维数组位置

huangapple go评论77阅读模式
英文:

Get twodimensional array positions out of integer

问题

我正在从图像中加载像素。
对于每个像素,我检查颜色并创建图像,现在我想将此图像添加到二维数组中。

int MAPWIDTH = 64; // 像素
int MAPHEIGHT = 16; // 像素
PImage[][] forGroundMap;

PImage file = loadImage(path);

file.loadPixels();

int size = file.width * file.height;

for (int i = 0; i < size; i++) {
    int x = i % MAPWIDTH;
    int y = i / MAPWIDTH;

    // forGroundMap[y][x] == 在这里写入相应的内容
}

供参考:这些图像的高度始终为64,宽度为32。

为了获取位置,我尝试通过当前迭代除以宽度,以知道我当前所在的行。

int divideBy(int number, int timesIn) {
    int count = 0;

    while (number >= timesIn) {
        number = number - timesIn;
        count++;
        println(number);
    }
    
    return count;
}

然而,这不能给我当前行内的列,并且我不确定这是否会起作用,以及如何继续前进。

英文:

I am loading pixels out of an image.
for every pixel I check the color and create an image, I now want to add this image inside of an two dimensional array.

int MAPWIDTH = 64; // in pixels
int MAPHEIGHT = 16; // in pixel
PImage[][] forGroundMap;

PImage file = loadImage(path);


file.loadPixels();
   
   int size = file.width * file.height;
   
   for (int i = 0; i &lt; size; i++) {

    int y = divideBy(i, MAPWIDTH);

    //forGroundMap[y][x] == something what is x and y here
   }

For reference: The images are always 64 in height and 32 in width.

To get the position I have tried to divide the current iteration by the width to know what row I am currently at.

int divideBy(int number, int timesIn) {
int count = 0;

while (number &gt;= timesIn) {
    number = number - timesIn;
    count++;
    println(number);
}

return count;

}

This however doesn't give me back the column inside my row And I am not sure if this will work at all and how to continue forward.

答案1

得分: 1

以下是翻译好的内容:

你似乎想要的是简单的除法数学运算。

int y = 1 / 64;
System.out.println(y);
y = 65 / 64;
System.out.println(y);

编辑

要同时获取 x 值,可以使用取余运算。

int x = 1 / 64;
int y = 1 % 64;
System.out.printf("你在位置 [%d,%d]%n", x, y);
x = 65 / 64;
y = 65 % 64;
System.out.printf("你在位置 [%d,%d]%n", x, y);
英文:

What you appears to be wanting is simple division math.

int y = 1 / 64;
System.out.println (y);
y = 65 / 64;
System.out.println (y);

edit

To get the x value as well use modulo

int x = 1 / 64;
int y = 1 % 64;
System.out.printf (&quot;you are at [%d,%d]%n&quot;, x,y);
x = 65 / 64;
y = 65 % 64;
System.out.printf (&quot;you are at [%d,%d]%n&quot;, x,y);

huangapple
  • 本文由 发表于 2020年10月2日 08:35:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64164843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定