2

我有一个使用 Bitmap.getPixels() 方法从位图派生的 int 数组。此方法使用位图中的像素填充数组。当我遍历该数组时,如何获得每个像素的 xy 坐标?在此先感谢垫。

[更新] 感谢您的数学。我试过下面的代码。我有一个位图,其中我将前 50000 像素更改为白色。我现在想遍历位图并将所有白色像素更改为红色。atm 只有一条红线穿过位图顶部的白色像素块。你有什么想法吗?多谢。

int length = bgr.getWidth()*bgr.getHeight();
                    int[] pixels = new int[length];
                    bgr.getPixels(pixels,0,bgr.getWidth(),0,0,bgr.getWidth(),bgr.getHeight());
                    for (int i=0;i<50000;i++){
                    // If the bitmap is in ARGB_8888 format

                        pixels[i] = Color.WHITE;//0xffffffff;

                      }

                    bgr.setPixels(pixels,0,bgr.getWidth(),0,0,bgr.getWidth(),bgr.getHeight());




                        int t = 0;
                    int y  = t / bgr.getWidth();
                    int x = t - (y * bgr.getWidth());

                  for( t = 0; t < length; t++){

                      int pixel = bgr.getPixel(x,y);

                      if(pixel == Color.WHITE){

                          bgr.setPixel(x,y,Color.RED);
                          x++;y++;
                      }
                  }
4

1 回答 1

7

这是一个代码示例,它可能符合您的描述。据我了解,至少你的目标;

int length = bgr.getWidth()*bgr.getHeight();
int[] pixels = new int[length];

bgr.getPixels(pixels,0,bgr.getWidth(),0,0,bgr.getWidth(),bgr.getHeight());

// Change first 50000 pixels to white. You most definitely wanted
// to check i < length too, but leaving it as-is.
for (int i=0;i<50000;i++){
    pixels[i] = Color.WHITE;
}

// I'm a bit confused why this is here as you have pixels[] to do
// modification on. And it would be a bit more efficient way to do all of
// these changes on pixels array before setting them back to bgr.
// But taken this is an experiment with Bitmaps (or homework, hopefully not ;)
// rather good idea actually.
bgr.setPixels(pixels, 0, bgr.getWidth(), 0, 0, bgr.getWidth(), bgr.getHeight());

for (int i=0; i < length; ++i) {
    int y = i / bgr.getWidth();
    int x = i - (y * bgr.getWidth());
    int pixel = bgr.getPixel(x, y);
    if(pixel == Color.WHITE){
        bgr.setPixel(x ,y , Color.RED);
    }
}
于 2011-05-07T18:13:37.853 回答