Floodfill algorithm in Android

被刻印的时光 ゝ 提交于 2019-12-23 09:25:09

问题


I am not able to find a floodfill algorithm implementation for Android.

Any idea if a floodfill API is available in Android, and if not, is there any other alternative?


回答1:


Do you have some definition of the shape?

If so, have a look at the Canvas docs. You can fill a region by defining a clip area and then calling canvas.drawColor.

Rough example:

    Rect r = new Rect(0,0,300,300);
    canvas.clipRect(r); // see also clipRegion
    canvas.drawColor(Color.RED);

There are several clip functions, so you should be able build whatever you're trying to fill.

On the other hand, if you want to floodfill a region in a loaded bitmap, then I don't know.




回答2:


FloodFill in android

public class FloodFill {
public void floodFill(Bitmap  image, Point node, int targetColor,
    int replacementColor) {
int width = image.getWidth();
int height = image.getHeight();
int target = targetColor;
int replacement = replacementColor;
if (target != replacement) {
    Queue<Point> queue = new LinkedList<Point>();
    do {
        int x = node.x;
        int y = node.y;
        while (x > 0 && image.getPixel(x - 1, y) == target) {
            x--;
        }
        boolean spanUp = false;
        boolean spanDown = false;
        while (x < width && image.getPixel(x, y) == target) {
            image.setPixel(x, y, replacement);
            if (!spanUp && y > 0 && image.getPixel(x, y - 1) == target) {
                queue.add(new Point(x, y - 1));
                spanUp = true;
            } else if (spanUp && y > 0
                    && image.getPixel(x, y - 1) != target) {
                spanUp = false;
            }
            if (!spanDown && y < height - 1
                    && image.getPixel(x, y + 1) == target) {
                queue.add(new Point(x, y + 1));
                spanDown = true;
            } else if (spanDown && y < height - 1
                    && image.getPixel(x, y + 1) != target) {
                spanDown = false;
            }
            x++;
        }
    } while ((node = queue.poll()) != null);
}
}
}

You should use a asynctask to use the floodfill algorithm. Using the same on the main thread caused out of memory error. Even if i use floofill algorithm sometime filling a huge area takes more time causing the application to become unresponsive at time.

Fill the complete canvas but keep the bound fill area as it is like circle, rectangle. This link could solve your problem



来源:https://stackoverflow.com/questions/4197416/floodfill-algorithm-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!