C#RotateTransform - 更改中心问题

时间:2016-03-19 15:42:50

标签: c# msdn rotatetransform

在我的C#程序中,我使用RotateTransform方法旋转我想要绘制的图片。 这已经有效,但我无法找到如何改变图片旋转的中心点。 默认情况下,它是我的Picturebox的左下角,不幸的是我需要围绕另一个点(760,480)px旋转。

我到处搜索过,只看到过这个CenterX属性。 CenterX msdn

无论如何,我似乎没有用Visual Studio找到这个属性, 所以我猜我做错了。

我目前的代码如下:

*e.Graphics.RotateTransform(angle);
e.Graphics.DrawLine(Pens.Black, physicObj.lineStartingPoint, physicObj.lineEndingPoint);
e.Graphics.FillEllipse(new SolidBrush(Color.Red), new Rectangle(physicObj.leftCornerCircle, physicObj.circleSize));
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), new Rectangle(physicObj.leftCornerRectangle, physicObj.rectangleSize));*

此部分工作正常,但使用错误的中心点旋转。 我试过用

e.Graphics.RotateTransform.CenterX = ... ;

但是在e.Graphics.RotateTransform中似乎没有可访问的CenterX。 Visual Studio在RotateTransform下面显示一条红线,表示它是一个方法,在给定的上下文中无效。 我不知道设置此属性的方法,我没有找到任何编码示例,并且基于Microsoft提供的信息(在链接中)我认为这是实现它的方法。

希望有人可以解释我需要做些什么来改变这个中心点。 谢谢!

1 个答案:

答案 0 :(得分:4)

这很简单:
1.翻译到中心
2.旋转
3.翻译回来

float centerX = 760;
float centerY = 480;
e.Graphics.TranslateTransform(-centerX, -centerY);
e.Graphics.RotateTransform(angle);
e.Graphics.TranslateTransform(centerX, centerY);

基本上,您创建3个矩阵并将它们相乘以获得结果 - 单个变换矩阵,2D和3D变换的基础。


附:为方便起见,您可以创建一个扩展方法:

public static class GraphicsExtensions
{
  public static void TranslateTransform(this Graphics g, float x, float y, float angle)
  {
    g.TranslateTransform(-x, -y);
    g.RotateTransform(angle);
    g.TranslateTransform(x, y);
  }
}