不說廢話,直接上代碼。(後篇會將基於掃描線的泛洪填充,會比基於鄰域的更快)
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using JsutATest.Api;
namespace JsutATest
{
public partial class Form1 : Form
{
Stack<int> stackRow = new Stack<int>();
Stack<int> stackColumn = new Stack<int>();
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
MouseEventArgs ex=e as MouseEventArgs;
Bitmap p = pictureBox1.Image as Bitmap;
FloodFill8WithStack(p, ex.X, ex.Y, Color.Red);
}
void CheckNewSeed(Bitmap p, int x, int y, Color oldValue, Color newValue)
{
if (x > 0 && x < p.Width && y > 0 && y < p.Height &&
p.GetPixel(x,y) == oldValue && p.GetPixel(x,y) != newValue)
{
p.SetPixel(x, y, newValue);
stackRow.Push(x);
stackColumn.Push(y);
}
}
public void FloodFill8WithStack(Bitmap p,int x, int y,Color newValue)
{
stackRow.Clear();
stackColumn.Clear();
stackRow.Push(x);
stackColumn.Push(y);
Color oldValue = p.GetPixel(x, y);
while (stackRow.Count > 0 && stackColumn.Count > 0)
{
x = stackRow.Pop();
y = stackColumn.Pop();
CheckNewSeed(p, x + 1, y,oldValue, newValue);
CheckNewSeed(p, x - 1, y,oldValue, newValue);
CheckNewSeed(p, x, y + 1,oldValue, newValue);
CheckNewSeed(p, x, y - 1,oldValue, newValue);
CheckNewSeed(p, x + 1, y + 1,oldValue, newValue);
CheckNewSeed(p, x - 1, y - 1,oldValue, newValue);
CheckNewSeed(p, x - 1, y + 1,oldValue, newValue);
CheckNewSeed(p, x + 1, y - 1,oldValue, newValue);
}
pictureBox1.Refresh();
p.Dispose();
}
}
}