從線條、曲線和形狀建立圖形

若要建立路徑,請建構 GraphicsPath 物件,然後呼叫方法,例如 AddLineAddCurve,以將基本類型新增至路徑。

下列範例會建立具有單一弧線的路徑。弧形的掃掠角度為 –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);

除了將線條和曲線新增至路徑之外,您還可以新增封閉圖形:矩形、橢圓形、pies 和多邊形。 下列範例會建立一個路徑,其中包含兩行、一個矩形和省略號。 程式碼會使用畫筆繪製路徑和筆刷來填滿路徑。

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::CloseFigureGraphicsPath::StartFigure,內部關閉的圖形,例如矩形和橢圓形,也會被視為個別的圖形。