從線條、曲線和圖形建立圖形
若要建立路徑,請建構 GraphicsPath 對象,然後呼叫方法,例如 AddLine 和 AddCurve,將基本類型新增至路徑。
下列範例會建立具有單一弧線的路徑。弧線的掃掠角度為 –180 度,在預設座標系統中是逆時針的。
Pen pen(Color(255, 255, 0, 0));
GraphicsPath path;
path.AddArc(175, 50, 50, 50, 0, -180);
graphics.DrawPath(&pen, &path);
下列範例會建立具有兩個圖形的路徑。 第一個圖是弧線後面接著一條線。 第二個圖是一條直線,接著一條曲線,再接著一條直線。 第一個圖保持開啟狀態,而第二個圖則為關閉狀態。
Point points[] = {Point(40, 60), Point(50, 70), Point(30, 90)};
Pen pen(Color(255, 255, 0, 0), 2);
GraphicsPath path;
// The first figure is started automatically, so there is
// no need to call StartFigure here.
path.AddArc(175, 50, 50, 50, 0.0f, -180.0f);
path.AddLine(100, 0, 250, 20);
path.StartFigure();
path.AddLine(50, 20, 5, 90);
path.AddCurve(points, 3);
path.AddLine(50, 150, 150, 180);
path.CloseFigure();
graphics.DrawPath(&pen, &path);
除了將線條和曲線新增至路徑之外,您還可以新增封閉圖形:矩形、橢圓形、餡餅和多邊形。 下列範例會建立一個路徑,其中包含兩行、一個矩形和橢圓形。 程式代碼會使用畫筆繪製路徑和筆刷來填滿路徑。
GraphicsPath path;
Pen pen(Color(255, 255, 0, 0), 2);
SolidBrush brush(Color(255, 0, 0, 200));
path.AddLine(10, 10, 100, 40);
path.AddLine(100, 60, 30, 60);
path.AddRectangle(Rect(50, 35, 20, 40));
path.AddEllipse(10, 75, 40, 30);
graphics.DrawPath(&pen, &path);
graphics.FillPath(&brush, &path);
上述範例中的路徑有三個數位。 第一個圖由兩行組成,第二個圖由矩形組成,而第三個圖則由橢圓形組成。 即使沒有呼叫 GraphicsPath::CloseFigure 或 GraphicsPath::StartFigure、內建封閉的圖形,例如矩形和省略號,都會被視為個別的圖形。