在Android中从图像中获取RGB颜色

时间:2014-12-17 15:25:48

标签: java android colors rgb

我制作游戏,在游戏中我使用图像加载地图。 我检查每个像素RGB并依赖于我添加对象。 这是我的代码:

        private void loadLevel() {
    Bitmap image = Assets.loadLevel(LEVEL);
    int w = image.getWidth();
    int h = image.getHeight();
    for (int xx = 0; xx < h; xx++) {
        for (int yy = 0; yy < w; yy++) {
            int pixel = image.getPixel(xx, yy);
            int red = (pixel >> 16) & 0xff;
            int green = (pixel >> 8) & 0xff;
            int blue = (pixel) & 0xff;

            if (red == 100 && green == 60 && blue == 0) { // / block
                Log.d("PlayState","Creating blockss!!!");
                addObject(new Block(xx * 32, yy * 32, 0, ObjectId.Block));

            }
            if (red == 100 && green == 50 && blue == 0) { // /block 1
                addObject(new Block(xx * 32, yy * 32, 1, ObjectId.Block));
            }
            if (red == 100 && green == 40 && blue == 0) { // /block 2
                addObject(new Block(xx * 32, yy * 32, 2, ObjectId.Block));
            }
            if (red == 100 && green == 30 && blue == 0) { // /block 3
                addObject(new Block(xx * 32, yy * 32, 3, ObjectId.Block));
            }
            if (red == 255 && green == 255 && blue == 255) { // /block 4
                addObject(new Block(xx * 32, yy * 32, 4, ObjectId.Block));
            }
            if (red == 255 && green == 255 && blue == 245) { // /block 5
                addObject(new Block(xx * 32, yy * 32, 7, ObjectId.Block));
            }
            if (red == 0 && green == 255 && blue == 33) { // /block up
                addObject(new Block(xx * 32, yy * 32, 5, ObjectId.Block));
            }
            if (red == 0 && green == 245 && blue == 33) { // /block up1
                addObject(new Block(xx * 32, yy * 32, 6, ObjectId.Block));
            }
            if (red == 0 && green == 0 && blue == 255) { // / player
                Log.d("PlayState","Creating Playerrr!!!");
                addObject(new Player(xx * 32, yy * 32, ObjectId.Player));

            }
        }
    }

}

问题在于,由于某种原因它只添加了Player对象,可能是因为它是唯一的红色和&amp;对象。绿色是0.当我使用完全相同的代码编程到Windows时,它工作得很好。

是的,我也试过了

            int red = Color.red(pixel);
            int green = Color.green(pixel);
            int blue = Color.blue(pixel);

同样的结果......

修改

如果其他人因为@JASONGPETERSON而遇到此问题,我找到了解决方案。 而不是寻找确切的值检查它是否有点低或更高,例如

if ((red > 90 && red < 110) && (green > 50 && green < 70) && blue == 0) { // / block
                Log.d("PlayState","Creating blockss!!!");
                addObject(new Block(xx * 32, yy * 32, 0, ObjectId.Block));

            }

3 个答案:

答案 0 :(得分:0)

您是否尝试使用红色,绿色和蓝色值来查看是否真的出现了这种情况?

答案 1 :(得分:0)

也许不能解决你的问题但是:

int pixel = image.getPixel(xx, yy);

建议你使用“xx”作为“x坐标”(宽度),但是你要在图像的高度上使用:

int h = image.getHeight();
for (int xx = 0; xx < h; xx++)

答案 2 :(得分:0)

也许您的条件需要测试窄范围而不是精确整数。由于getPixel()方法,图像压缩等原因,可能会有一些舍入(事实上,事实证明这很有效。)

相关问题