Skip to content

Instantly share code, notes, and snippets.

@ribasco
Last active January 5, 2020 12:00
Show Gist options
  • Save ribasco/9b7618da5530eb75f03f4ea711fe07a5 to your computer and use it in GitHub Desktop.
Save ribasco/9b7618da5530eb75f03f4ea711fe07a5 to your computer and use it in GitHub Desktop.
[JavaFX] Flood Fill Algorithm (Recursive iteration approach)
public class DrawUtil {
private static class FillParams {
int x;
int y;
Color selectedColor;
private FillParams(int x, int y, Color selectedColor) {
this.x = x;
this.y = y;
this.selectedColor = selectedColor;
}
}
/**
* Flood fill algorithm. Uses the iterative approach to prevent {@link StackOverflowError}
*
* @param x
* The x-coordinate of the pixel
* @param y
* The y-coordinate of the pixel
*
* @return The {@link FillDrawAction} containing all points of the filled surface
*/
public static FillDrawAction floodFill(WritableImage image, int x, int y, Color newColor) {
var pw = image.getPixelWriter();
var pr = image.getPixelReader();
Color selectedColor = pr.getColor(x, y);
final Stack<FillParams> paramStack = new Stack<>();
paramStack.push(new FillParams(x, y, selectedColor));
FillDrawAction parentAction = getAction(true);
if (newColor == null)
newColor = selectedColor.equals(Color.TRANSPARENT) ? Color.BLACK : Color.TRANSPARENT;
while (!paramStack.isEmpty()) {
final FillParams param = paramStack.pop();
if (param.x < 0 || param.x >= image.getWidth() || param.y < 0 || param.y >= image.getHeight())
continue;
Color current = pr.getColor(param.x, param.y);
if (current.equals(newColor) || !param.selectedColor.equals(current))
continue;
parentAction.addChild(new FillDrawAction(param.x, param.y));
pw.setColor(param.x, param.y, newColor);
getCanvas().invalidate();
paramStack.push(new FillParams(param.x - 1, param.y, selectedColor)); //West
paramStack.push(new FillParams(param.x + 1, param.y, selectedColor)); //East
paramStack.push(new FillParams(param.x, param.y + 1, selectedColor)); //South
paramStack.push(new FillParams(param.x, param.y - 1, selectedColor)); //North
}
return parentAction;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment