Flood Fill Algorithms

前端 未结 7 2243
借酒劲吻你
借酒劲吻你 2020-11-30 08:40

Its the weekend again, and that means I get to play with my hobby project.

I\'ve gotten tired of creating test levels by hand, so I thought I\'d take a break from en

7条回答
  •  执笔经年
    2020-11-30 08:52

    Simple function without check the color tolerance

    Using:

    var img = Image.FromFile("test.png");
    img = img.FloodFill(new Point(0, 0), Color.Red);
    img.Save("testcomplete.png", ImageFormat.Png);
    

    Main function:

        public static Image FloodFill(this Image img, Point pt, Color color)
        {
            Stack pixels = new Stack();
            var targetColor = ((Bitmap)img).GetPixel(pt.X, pt.Y);
            pixels.Push(pt);
    
            while (pixels.Count > 0)
            {
                Point a = pixels.Pop();
                if (a.X < img.Width && a.X > -1 && a.Y < img.Height && a.Y > -1)
                {
                    if (((Bitmap)img).GetPixel(a.X, a.Y) == targetColor)
                    {
                        ((Bitmap)img).SetPixel(a.X, a.Y, color);
                        pixels.Push(new Point(a.X - 1, a.Y));
                        pixels.Push(new Point(a.X + 1, a.Y));
                        pixels.Push(new Point(a.X, a.Y - 1));
                        pixels.Push(new Point(a.X, a.Y + 1));
                    }
                }
            }
            return img;
        }
    

提交回复
热议问题