C#中級 コーディング例
G11)許容量付ペイント
許容量(0〜255)を設定して近似色をペイント
//bmp:対象イメージ画像
void FillApprox(Bitmap bmp, Point point, Color fill, int tolerance)
{
Color target = bmp.GetPixel(point.X, point.Y);//クリック位置の色取得
//塗る領域の設定
Point areaMinPoint = new Point(0,0);
Point areaMaxPoint = new Point(bmp.Width, bmp.Height);
int w = bmp.Width, h = bmp.Height;
bool[,] vis = new bool[w, h];
var st = new Stack<Point>();
st.Push(new Point(point.X, point.Y));
while (st.Count > 0)
{
var p = st.Pop();
int x = p.X, y = p.Y;
if (x < areaMinPoint.X || x >= areaMaxPoint.X || y < areaMinPoint.Y || y >= areaMaxPoint.Y) continue;
if (vis[x, y]) continue;
Color c = bmp.GetPixel(x, y);
if (!Similar(c, target, tolerance)) continue;
vis[x, y] = true;
bmp.SetPixel(x, y, fill);
st.Push(new Point(x + 1, y));
st.Push(new Point(x - 1, y));
st.Push(new Point(x, y + 1));
st.Push(new Point(x, y - 1));
}
pictureBox.Image = bmp;
}
bool Similar(Color a, Color b, int tol)
{
int dr = a.R - b.R;
int dg = a.G - b.G;
int db = a.B - b.B;
// RGB 各成分は 0〜255
// 距離の二乗 <= tol^2 なら「近似色」
return dr * dr + dg * dg + db * db <= tol * tol;
}


元画像 ペイントサンプル