你會循環從上到下的「形象」。
對於每一行,您都會從左向右循環,從「outside」開始。每次當你穿過你正在看的當前線的垂直線時,你就會翻轉「外側/內側」位。
然後你着色裏面的所有廣場。
這裏有一個LINQPad程序演示:
const int scale = 20;
void Main()
{
var polyline = new[]
{
new Point(4, 0),
new Point(4, 5),
new Point(10, 5),
new Point(10, 10),
new Point(6, 10),
new Point(6, 3),
new Point(15, 3),
new Point(15, 8),
new Point(14, 8),
new Point(14, 7),
new Point(16, 7),
new Point(16, 0),
};
int maxY = polyline.Max(point => point.Y);
int maxX = polyline.Max(point => point.X);
var bitmap = new Bitmap((maxX + 1) * scale, (maxY + 1) * scale);
var previousPoint = polyline[0];
using (var g = Graphics.FromImage(bitmap))
{
// TODO: y=0 should be y = minY - 1
for (int y = 0; y < maxY + 1; y++)
{
bool isInside = false;
var xCoordinatesOfCrossingLines = new HashSet<int>(
from index in Enumerable.Range(0, polyline.Length)
let p1 = polyline[index]
let p2 = polyline[(index + 1) % polyline.Length]
where p1.X == p2.X
where (p1.Y <= y && p2.Y > y) // must cross the y-slice in downwards
|| (p2.Y <= y && p1.Y > y) // or upwards direction
let x = p1.X
group x by x into xGroup // if we somehow have 2 (or an even number of) lines overlapping, don't count them
where xGroup.Count() % 2 != 0 // so we will only except distinct x values that occur 1, 3, 5, etc. times
select xGroup.Key);
// TODO: x=0 should be x = minX - 1
for (int x = 0; x < maxX + 1; x++)
{
// Every time we hit a vertical line, we flip the "is inside" bit
if (xCoordinatesOfCrossingLines.Contains(x))
isInside = !isInside;
// Colorize all the squares inside
if (isInside)
g.FillRectangle(Brushes.Green, new Rectangle(
ScalePoint(new Point(x, y), scale),
new Size(scale, scale)));
}
}
for (int index = 1; index <= polyline.Length; index++)
{
g.DrawLine(Pens.Black, ScalePoint(previousPoint, scale), ScalePoint(polyline[index % polyline.Length], scale));
previousPoint = polyline[index % polyline.Length];
}
}
bitmap.Dump();
}
public Point ScalePoint(Point p, int scale)
{
return new Point(p.X * scale, p.Y * scale);
}
輸出:
算法變換的輸入到輸出僅終止。你的輸出是什麼?像素?簡單的多邊形?凸多邊形? –
像素。多邊形是一組或多個矩形。 – Haradzieniec
你有所有的線路點或只有開始和結束?你的輸入數據是什麼? – Grundy