CShap flood fill 源代码
时间: 2023-10-17 15:05:37 浏览: 95
以下是C#语言的Flood Fill算法源代码:
```
using System;
using System.Collections.Generic;
using System.Drawing;
namespace FloodFillAlgorithm
{
public class FloodFill
{
private Bitmap _bitmap;
private Color _fillColor;
private Color _targetColor;
public FloodFill(Bitmap bitmap)
{
_bitmap = bitmap;
}
public void Fill(int x, int y, Color fillColor)
{
_fillColor = fillColor;
_targetColor = _bitmap.GetPixel(x, y);
if (_fillColor == _targetColor)
return;
Queue<Point> pixels = new Queue<Point>();
pixels.Enqueue(new Point(x, y));
while (pixels.Count > 0)
{
Point currentPixel = pixels.Dequeue();
if (currentPixel.X < 0 || currentPixel.X >= _bitmap.Width || currentPixel.Y < 0 || currentPixel.Y >= _bitmap.Height)
continue;
if (_bitmap.GetPixel(currentPixel.X, currentPixel.Y) != _targetColor)
continue;
_bitmap.SetPixel(currentPixel.X, currentPixel.Y, _fillColor);
pixels.Enqueue(new Point(currentPixel.X - 1, currentPixel.Y));
pixels.Enqueue(new Point(currentPixel.X + 1, currentPixel.Y));
pixels.Enqueue(new Point(currentPixel.X, currentPixel.Y - 1));
pixels.Enqueue(new Point(currentPixel.X, currentPixel.Y + 1));
}
}
}
}
```
此代码实现了基本的Flood Fill算法,使用了一个队列来存储待处理的像素点。每次从队列中取出一个像素点,检查它是否在位图范围内以及是否与目标颜色相同,如果是,则将其颜色设置为填充颜色,并将其周围的像素点加入队列中等待处理。
阅读全文