還有一點值得做的是,AddLine()創建的GraphicsPath的線路,但線路沒有實際寬度(即0寬度)因此爲什麼不相交。
你需要在每行上給它們一些實際的寬度調用Widen(),然後它們有一個可以相互交叉的區域。
我有低於一個小例子展示瞭如何解決這個問題 - 這是寫有LinqPad使用...
void Main()
{
Panel panel = new Panel();
Graphics g = panel.CreateGraphics();
Pen p = new Pen(Color.Black, 1);
GraphicsPath rect = new GraphicsPath();
rect.AddRectangle(new Rectangle(0, 0, 10, 10));
GraphicsPath li = new GraphicsPath(); // Intersects with Rect
li.AddLine(new Point(1, 1), new Point(20, 10));
li.Widen(p);
GraphicsPath lc = new GraphicsPath(); // Contained in Rect
lc.AddLine(new Point(1, 1), new Point(2, 2));
lc.Widen(p);
GraphicsPath ln = new GraphicsPath(); // Not contained or intersect
ln.AddLine(new Point(20, 20), new Point(30, 20));
ln.Widen(p);
HitTest(rect, li, g);
HitTest(rect, lc, g);
HitTest(rect, ln, g);
g.Dispose();
panel.Dispose();
}
private void HitTest(GraphicsPath a, GraphicsPath b, Graphics g)
{
Region ar = new Region(a);
Region br = new Region(b);
Region cr1 = ar.Clone();
Region cr2 = ar.Clone();
cr1.Union(br);
cr2.Intersect(br);
if (cr2.IsEmpty(g))
("No Intersect, No Contain").Dump();
else if (cr1.Equals(ar, g))
("Contain").Dump();
else
("Intersect").Dump();
}
區則被設計成封裝一組像素。它必須包含至少1 x 1像素不能爲空。兩條線的交點不夠大。兩個多邊形,至少1個像素寬,將工作。 –