我需要编写一个填充算法来为黑色边框内的图像像素着色。我根据 SO 上的一些帖子写了以下内容:
private Queue<Point> queue = new LinkedList<Point>();
private int pickedColorInt = 0;
private void floodFill(Pixmap pixmap, int x, int y){
//set to true for fields that have been checked
boolean[][] painted = new boolean[pixmap.getWidth()][pixmap.getHeight()];
//skip black pixels when coloring
int blackColor = Color.rgba8888(Color.BLACK);
queue.clear();
queue.add(new Point(x, y));
while(!queue.isEmpty()){
Point temp = queue.remove();
int temp_x = temp.getX();
int temp_y = temp.getY();
//only do stuff if point is within pixmap's bounds
if(temp_x >= 0 && temp_x < pixmap.getWidth() && temp_y >= 0 && temp_y < pixmap.getHeight()) {
//color of current point
int pixel = pixmap.getPixel(temp_x, temp_y);
if (!painted[temp_x][temp_y] && pixel != blackColor) {
painted[temp_x][temp_y] = true;
pixmap.drawPixel(temp_x, temp_y, pickedColorInt);
queue.add(new Point(temp_x + 1, temp_y));
queue.add(new Point(temp_x - 1, temp_y));
queue.add(new Point(temp_x, temp_y + 1));
queue.add(new Point(temp_x, temp_y - 1));
}
}
}
}
这没有按预期工作。例如,在以下测试图像上:
随机矩形将根据我点击的位置重新着色。例如,单击紫色矩形下方的任意位置将重新着色紫色矩形。在紫色矩形内部单击会重新着色绿色矩形。我已经检查过了,我正在将正确的参数传递给方法,所以问题可能出在我的循环中。
最佳答案
你的算法是正确的,只是你的输入参数不正确。
Random rectangles will get recolored depending of where I've clicked. For example, clicking anywhere below purple rectangle will recolor purple rectangle. Clicking inside purple rectangle recolors the green rectangle.
如果您看图片,彩色矩形并不是真正随机的。真正的问题是 Y 坐标不正确。具体来说,您的 Y 坐标是倒置的。
那是因为大多数时候 LibGDX 使用左下、y 向上的坐标系统,但在 Pixmap
的情况下,它是左上 y 向下。
解决此问题的一个简单方法是通过执行 y = pixmap.getHeight() - y
来反转 Y 值。
关于Java 洪水填充问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29914125/