【发布时间】:2009-09-28 06:54:10
【问题描述】:
我正在控件上绘制图形,但 0,0 在控件的左上角。有没有办法翻转坐标使0,0在控件的左下角?
【问题讨论】:
-
您使用的是 WinForms 还是 WPF?您可能想更新问题的标签。
标签: c# .net winforms custom-controls
我正在控件上绘制图形,但 0,0 在控件的左上角。有没有办法翻转坐标使0,0在控件的左下角?
【问题讨论】:
标签: c# .net winforms custom-controls
如果您使用的是 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...
}
如果您还想使用常规坐标系进行其他绘图,则只需包含开始/结束容器调用。更多关于图形容器的信息是available on MSDN。
正如 Tom 在 cmets 中提到的,这种方法要求 Height 值具有正确的值。如果您尝试此操作但没有绘制任何内容,请确保该值在调试器中正确。
【讨论】:
这是一个简单的 UserControl,它演示了如何执行此操作:
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。
【讨论】:
我不知道,但如果你使用 (x,Control.Height-y) 你会得到同样的效果。
【讨论】:
简而言之,不,但是如果我经常使用控件,我有一些功能可以帮助我:
Point GraphFromRaster(Point point) {...}
Point RasterFromGraph(Point point) {...}
这样我把所有的转换都保存在一个地方,不用担心像y - this.Height这样的东西分散在代码中。
【讨论】: