2009-09-28 94 views
9

我正在绘制控件上的图形,但是0,0位于控件的左上角。有没有办法翻转坐标,使0,0位于控件的左下角?绘图控制时的翻转坐标

+0

您正在使用的WinForms或WPF?你可能想更新你问题上的标签。 –

回答

13

如果您正在使用的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

正如汤姆在评论中提到的那样,这种方法要求Height值具有正确的值。如果您尝试此操作并且看不到任何内容正在绘制,请确保调试器中的值是正确的。

+0

您还需要添加翻译才能正常工作。 – Eric

+0

谢谢埃里克。我已经更新了我的答案,并包含了使用图形容器将这些转换与其他更改隔离的信息。 –

+0

没有为我工作。我还不是WinForms。事实证明,“身高”与当前的控制无关。我在我的面板中打了这个电话。打了一下,没有画任何东西。提到你假设你正在绘制表单本身可以节省一些时间,因为它可以节省我一些调试时间;) – Tom

0

不,但使用控件的Size(或Height)属性,很容易计算翻转的坐标:只需绘制到Height-y即可。

0

不是说我知道,但如果你使用(x,Control.Height-y),你会得到相同的效果。

-1
总之

没有,但是如果我在控制借鉴了很多我有几个功能,帮助我:

Point GraphFromRaster(Point point) {...} 
Point RasterFromGraph(Point point) {...} 

这样,我把所有的转换在一个地方,不担心这样的事情y - this.Height散乱的代码。

+0

为什么投下来? – Pondidum

1

这里有一个简单的用户控件演示如何做到这一点:

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); 
    } 
}