Java BufferedImage像素[]获得正确的像素

时间:2014-09-21 01:05:04

标签: java arrays canvas pixel

您好我试图使用我从

获得的像素数组绘制一个矩形
pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();

但我似乎无法获得正确的像素。

我试图使用

public void p_fillRect(int color, int x, int y, int width, int height) {
    for (int xpos = x; xpos < width; xpos++) {
        for (int ypos = y; ypos < height; ypos++) {
            pixels[xpos + ypos * em.getGame().getWidth()] = color;
        }
    }
} 

但它没有按照我的预期工作,请帮忙!

以下是循环当前状态的链接:http://imgur.com/v0tjsYe

以下是该计划结果的链接:http://imgur.com/OrTxNUk

1 个答案:

答案 0 :(得分:0)

一些问题/建议。

em.getGame().getWidth()您正在访问像素的缓冲图像的宽度?

你也可以尝试切换yPos和xPos变量,这样你的数组看起来就像这样:

for(int ypos = y; ypos < height ypos++){
    for(int xpos = x; xpos < width; xpos++){
        pixels[xpos + ypos em.getGame().getWidth()] = color;
    }
}

你是什么意思,你似乎无法获得正确的像素?矩形是否显示在错误的位置?

编辑:此方法适用于我

BufferedImage canvas = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_RGB);

Raster raster = canvas.getRaster();
int[] pixels = ((DataBufferInt) raster.getDataBuffer()).getData();

public void fillRect(int xPos, int yPos, int width, int height){
    for(int y = 0; y < height; y++){
        for(int x = 0; x < width; x++){
            pixels[(x*canvasWidth)+y] = someColor;
        }
    }
}

我像这样渲染画布:

g.drawImage(canvas, 0,0, canvasWidth, canvasHeight);
相关问题