全局变换和局部变换

全局转换是应用于给定 Graphics 对象绘制的每个项的转换。 若要创建全局转换,请构造 Graphics 对象,然后调用其 Graphics::SetTransform 方法。 Graphics::SetTransform 方法操作与 Graphics 对象关联的 Matrix 对象。 存储在该 Matrix 对象中的转换称为 世界转换。 世界转换可以是一个简单的仿射转换或一系列复杂的仿射转换,但无论其复杂程度如何,世界转换都存储在单个 Matrix 对象中。

Graphics 类提供了几种用于构建复合世界转换的方法:Graphics::MultiplyTransformGraphics::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 轴的屏幕截图,以及覆盖在半透明直角周围旋转的蓝色正方形的屏幕截图