【发布时间】:2011-08-24 13:16:59
【问题描述】:
我有一张地图的图像和一个较小的 PictureBox 控件。
我正在从我的 Joysyick 那里得到输入。我的 Y 将图像向上并离开 加上 X 实际上旋转图像..
我的问题是当我旋转图像时,Y 轴也随之旋转,所以当我再次向上移动时,它不会真正向上移动.. 它也会向 Y 轴指向的新方向移动..
如果你能理解我的问题,这是我的代码..
public void UpdateTurret()
{
while (js != null)
{
js.GetData();
Thread.Sleep(80);
MapY += js.State.Y;
MapRotation += js.State.X;
{
Image map = Properties.Resources.Map;
Bitmap bmp = (Bitmap)map.Clone();
Graphics g = Graphics.FromImage((Image)bmp);
g.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2 - (MapY / 2));
g.RotateTransform(MapRotation);
g.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2 + (MapY / 2));
g.DrawImage(bmp, 0, 0);
Graphics gfx = Graphics.FromImage((Image)bmp);
gfx.DrawPie(new Pen(Color.Blue, 5), bmp.Width/2 - 5, bmp.Height/2 - 5, 5, 5, 0, 360);
gfx.DrawImage(bmp, 0, MapY);
picBoxMap.Image = (Image)bmp;
float rot = MapRotation;
rot = (float)Math.Abs((rot - 360*Math.Ceiling(rot / 360)));
DrawString = (rot).ToString() + "° Y:" + MapY.ToString();
}
}
}
我现在的问题是旋转点总是居中,我希望我的旋转点是我到达的新位置。
所以我想它应该是这样的:
g.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2 - MapY);
g.RotateTransform(MapRotation);
g.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2 + MapY);
但这会导致另一个错误。现在,当我旋转图像时,Y 轴也随之旋转,所以当我再次向上移动时,它不会真正向上移动。它也会向 Y 轴指向的新方向移动。
有人有解决这个问题的想法吗?
编辑:
这是我的新代码:
public void UpdateTurret()
{
while (js != null)
{
js.GetData();
Thread.Sleep(80);
MapY += js.State.Y;
MapRotation += js.State.X;
{
Image map = Properties.Resources.Map;
Size mapSize = map.Size;
Bitmap bmp = (Bitmap)map.Clone();
Graphics g = Graphics.FromImage((Image)bmp);
Matrix transformMatrix = new Matrix();
transformMatrix.Translate(-mapSize.Width / 2, -mapSize.Height / 2, MatrixOrder.Append);
transformMatrix.Rotate(MapRotation, MatrixOrder.Append);
transformMatrix.Translate(mapSize.Width / 2, mapSize.Height / 2, MatrixOrder.Append);
transformMatrix.Translate(0, MapY, MatrixOrder.Append);
g.Transform = transformMatrix;
g.DrawImage(bmp, 0,0);
picBoxMap.Image = (Image)bmp;
float rot = MapRotation;
rot = (float)Math.Abs((rot - 360*Math.Ceiling(rot / 360)));
DrawString = (rot).ToString() + "° Y:" + MapY.ToString();
}
}
//Draw Cross
Graphics gfx = picBoxMap.CreateGraphics();
Rectangle rc = picBoxMap.ClientRectangle;
gfx.DrawLine(Pens.Red, rc.Width / 2, rc.Height / 2 + 10, rc.Width / 2, rc.Height / 2 - 10);
gfx.DrawLine(Pens.Red, rc.Width / 2 + 10, rc.Height / 2, rc.Width / 2 - 10, rc.Height / 2);
}
我现在的问题是,我在 Y 轴上移动地图后,旋转点停留在中心点上。
并且照顾我只旋转了地图:
你可以看到我没有移动 Y 轴,但它确实改变了。因为旋转点在图像的中心,而不是红十字的位置。
我需要旋转点在红十字的同一位置。
【问题讨论】:
-
看看
Graphics.Transform和Matrix.Rotate/Matrix.Translate方法。它比做你正在做的事情(在每次变换后绘制图像)要简单得多。 -
@George 嘿,你能给我举个例子吗?我以前从未使用过 Tranfrom / Matrix ...