Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java BuffereImage pixel[]获取正确的像素_Java_Arrays_Canvas_Pixel - Fatal编程技术网

Java BuffereImage pixel[]获取正确的像素

Java BuffereImage pixel[]获取正确的像素,java,arrays,canvas,pixel,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

你好,我想用我从中得到的像素阵列画一个矩形

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;
        }
    }
} 
public void p_fillRect(int color,int x,int y,int width,int height){
对于(int xpos=x;xpos
但它并没有像我期望的那样工作,请帮忙


以下是指向循环当前状态的链接:


以下是该计划结果的链接:

几个问题/建议

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;
    }
}

是。getGame().getWidth()正在获取BuffereImage的宽度。它看起来不像我想象中的矩形,更不像是一条粗斜线。我真正需要知道的是如何从一维像素阵列中获得二维空间中的像素。更不用说我如何用一个一维数组做像素[x][y]。@Kuliu你的公式是对的,x+(y*width)。你试过改变你的循环了吗?您的原始循环先迭代x,然后迭代y。对于这个公式,你的循环应该先迭代y,然后迭代x(如这个答案所示)是的,我试图改变它,但它给了我相同的结果:(这是指向循环当前状态的链接:这是程序结果的链接:@Kuliu如果在我的编辑中发布的解决方案仍然不起作用,我可以发布我的完整代码。为什么不使用BuffereImage.setRGB(int x,int y,int 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);