Wikipedia has a great article on flood fill algorithms. I had some issues dealing with screen dithering when trying repeated flood fills, and of course, performance. The following snippet is from my flood fill routine.
Using java Syntax Highlighting
private void floodFill(int index, int[] pixels, int w, int paintColor) {
Stack stack = new Stack(pixels.length);
stack.push(index);
pixels[index] = paintColor;
// loop has a seed pixel that has been been transformed to newColor
int scanLeft;
int scanRight;
while (stack.hasQueue()) {
scanLeft = index;
scanRight = index;
// replace pixels to left boundary
while ((scanLeft % w != 0) && isInColorRange(pixels[scanLeft - 1])) {
scanLeft--;
pixels[scanLeft] = paintColor;
}
// replace pixels to right boundary
while ((scanRight % w != w - 1) && isInColorRange(pixels[scanRight + 1])) {
scanRight++;
pixels[scanRight] = paintColor;
}
// check line above for target color & populate stack
if (scanLeft - w >= 0) {
for (int i = scanLeft - w; i <= scanRight - w; i += 1) {
if (isInColorRange(pixels[i])) {
pixels[i] = paintColor;
stack.push(i);
}
}
}
// check line below for target color & populate stack
if (scanRight + w < pixels.length) {
for (int i = scanLeft + w; i <= scanRight + w; i += 1) {
if (isInColorRange(pixels[i])) {
pixels[i] = paintColor;
stack.push(i);
}
}
}
index = stack.pop();
}
}
/*
* Used as a queue for the Fill Loop: Floodfill
*/
private class Stack {
int mIndex;
int[] mStack;
Stack(int size) {
mStack = new int[size];
mIndex = 0;
}
void push(int pixelIndex) {
mStack[++mIndex] = pixelIndex;
}
int pop() {
return mStack[mIndex--];
}
boolean hasQueue() {
return (mIndex > 0) ? true : false;
}
}
}
Parsed in 0.037 seconds, using
GeSHi 1.0.8.4