我正在一个控件上绘制图形,但是0,0位于控件的左上角。是否有一种方法可以翻转坐标轴使得0,0位于控件的左下角?
我正在一个控件上绘制图形,但是0,0位于控件的左上角。是否有一种方法可以翻转坐标轴使得0,0位于控件的左下角?
如果您正在使用WinForms,则可以使用Graphics.ScaleTransform翻转Y轴:
private void ScaleTransformFloat(PaintEventArgs e)
{
// Begin graphics container
GraphicsContainer containerState = e.Graphics.BeginContainer();
// Flip the Y-Axis
e.Graphics.ScaleTransform(1.0F, -1.0F);
// Translate the drawing area accordingly
e.Graphics.TranslateTransform(0.0F, -(float)Height);
// Whatever you draw now (using this graphics context) will appear as
// though (0,0) were at the bottom left corner
e.Graphics.DrawRectangle(new Pen(Color.Blue, 3), 50, 0, 100, 40);
// End graphics container
e.Graphics.EndContainer(containerState);
// Other drawing actions here...
}
只需在需要使用常规坐标系进行其他绘图时,才需要包含起始/结束容器调用。有关图形容器的更多信息,请参见MSDN上的相关内容。
正如Tom在评论中提到的那样,此方法要求Height
值可用且具有正确的值。如果尝试此操作但未看到任何绘制内容,请在调试器中确保该值正确。
public partial class UserControl1 : UserControl
{
public UserControl1()
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.ScaleTransform(1.0F, -1.0F);
e.Graphics.TranslateTransform(0.0F, -(float)Height);
e.Graphics.DrawLine(Pens.Black, new Point(0, 0), new Point(Width, Height));
base.OnPaint(e);
}
}
不过,使用控件的 Size
(或 Height
)属性,可以轻松计算翻转坐标:只需绘制到 Height-y
。
简而言之不行,但如果我需要频繁地操作控件,我有一些帮助我的函数:
Point GraphFromRaster(Point point) {...}
Point RasterFromGraph(Point point) {...}
这样我可以将所有的转换都放在一个地方,不必担心像y - this.Height
这样散落在代码中的事情。
我不知道有没有,但如果你使用 (x,Control.Height-y),你会得到相同的效果。