The first such method that we will discuss is called the boundary-fill algorithm. The boundary-fill method requires the coordinate of a starting point, a fill color, and a background color as arguments.
public void boundaryFill(int x, int y, int fill, int boundary) {
if ((x < 0) || (x >= raster.width)) return;
if ((y < 0) || (y >= raster.height)) return;
int current = raster.getPixel(x, y);
if ((current != boundary) & (current != fill)) {
raster.setPixel(fill, x, y);
boundaryFill(x+1, y, fill, boundary);
boundaryFill(x, y+1, fill, boundary);
boundaryFill(x-1, y, fill, boundary);
boundaryFill(x, y-1, fill, boundary);
}
}
Note: that this is a recusive routine. Each invocation of
boundaryFill( ) may call itself four more times.
The logic of this routine is very simple. If we are not either on a boundary or already filled we first fill our point, and then tell our neighbors to fill themselves.