全域和區域轉換

全域轉換是套用至指定 Graphics 物件所繪製之每個專案的轉換。 若要建立全域轉換,請建構 Graphics 物件,然後呼叫其 Graphics::SetTransform 方法。 Graphics::SetTransform方法會操作與Graphics物件相關聯的Matrix物件。 儲存在該 Matrix 物件的轉換稱為 世界轉換。 世界轉換可以是簡單的相依轉換或複雜序列的相依轉換,但不論其複雜度為何,世界轉換都會儲存在單一 Matrix 物件中。

Graphics類別提供數種方法來建置複合世界轉換:Graphics::MultiplyTransform、Graphics::RotateTransformGraphics::ScaleTransformGraphics::TranslateTransform。 下列範例會繪製省略號兩次:建立世界轉換之前,一次之後再繪製一次。 轉換會先以 Y 方向 0.5 的倍數縮放,然後轉譯 x 方向的 50 單位,然後旋轉 30 度。

myGraphics.DrawEllipse(&myPen, 0, 0, 100, 50);
myGraphics.ScaleTransform(1.0f, 0.5f);
myGraphics.TranslateTransform(50.0f, 0.0f, MatrixOrderAppend);
myGraphics.RotateTransform(30.0f, MatrixOrderAppend);
myGraphics.DrawEllipse(&myPen, 0, 0, 100, 50);

下圖顯示原始省略號和已轉換的橢圓形。

包含兩個重迭橢圓形的視窗螢幕擷取畫面;一個較窄且旋轉

注意

在上一個範例中,橢圓形會旋轉座標系統的原點,而座標系統位於工作區的左上角。 這會產生不同于旋轉橢圓形本身中心的結果。

 

本機轉換是套用至要繪製之特定專案的轉換。 例如,GraphicsPath 物件具有 GraphicsPath::Transform方法,可讓您轉換該路徑的資料點。 下列範例會繪製沒有轉換的矩形,以及具有旋轉轉換的路徑。 (假設沒有世界轉型。)

 
Matrix myMatrix;
myMatrix.Rotate(45.0f);
myGraphicsPath.Transform(&myMatrix);
myGraphics.DrawRectangle(&myPen, 10, 10, 100, 50);
myGraphics.DrawPath(&myPen, &myGraphicsPath);

您可以將世界轉型與本機轉換結合,以達成各種結果。 例如,您可以使用世界轉換來修改座標系統,並使用本機轉換來旋轉和縮放在新座標系統上繪製的物件。

假設您想要一個座標系統,其原點從工作區左邊緣 200 圖元,以及來自工作區頂端的 150 圖元。 此外,假設您想要測量單位是圖元,而 X 軸指向右邊,而 Y 軸指向上。 預設座標系統有 Y 軸向下指向,因此您需要跨水準軸執行反映。 下圖顯示這類反映的矩陣。

顯示三對三矩陣的圖例

接下來,假設您需要在右邊執行 200 個單位的翻譯,並向下執行 150 個單位。

下列範例會藉由設定 Graphics 物件的世界轉換來建立剛描述的座標系統。

Matrix myMatrix(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f);
myGraphics.SetTransform(&myMatrix);
myGraphics.TranslateTransform(200.0f, 150.0f, MatrixOrderAppend);

下列程式碼 (放在上述範例中的程式碼之後,) 建立一個路徑,其中包含位於新座標系統原點的單一矩形及其左下角。 矩形會填滿一次,沒有本機轉換,一次使用本機轉換。 本機轉換是由 2 倍的水準縮放所組成,後面接著 30 度旋轉。

// Create the path.
GraphicsPath myGraphicsPath;
Rect myRect(0, 0, 60, 60);
myGraphicsPath.AddRectangle(myRect);

// Fill the path on the new coordinate system.
// No local transformation
myGraphics.FillPath(&mySolidBrush1, &myGraphicsPath);

// Transform the path.
Matrix myPathMatrix;
myPathMatrix.Scale(2, 1);
myPathMatrix.Rotate(30, MatrixOrderAppend);
myGraphicsPath.Transform(&myPathMatrix);

// Fill the transformed path on the new coordinate system.
myGraphics.FillPath(&mySolidBrush2, &myGraphicsPath);

下圖顯示新的座標系統和兩個矩形。

x 和 y 軸的螢幕擷取畫面,以及由半透明重迭繞其左下角旋轉的藍色方塊