【问题标题】:flip coordinates when drawing to control绘制控制时翻转坐标
【发布时间】:2009-09-28 06:54:10
【问题描述】:

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

【问题讨论】:

  • 您使用的是 WinForms 还是 WPF?您可能想更新问题的标签。

标签: c# .net winforms custom-controls


【解决方案1】:

如果您使用的是 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 值具有正确的值。如果您尝试此操作但没有绘制任何内容,请确保该值在调试器中正确。

【讨论】:

  • 谢谢埃里克。我更新了我的答案,并包含了有关使用图形容器将这些转换与其他更改隔离开来的信息。
  • 对我不起作用。我还不是 WinForms 奇才。事实证明,“高度”与当前控件无关。我在我的 panel.OnPaint 中调用了它,但没有绘制任何内容。提到您假设您在表单本身上绘图可以节省其他人一些时间,因为它可以节省我一些调试时间;)
  • @Tom,我根据您的经验添加了一个说明。谢谢。
  • @DrewNoakes,这个解决方案不完整,导致 DrawString 生成的文本无效,例如垂直翻转。
  • 完全正确。如果您正在绘制文本,这将不起作用。
【解决方案2】:

这是一个简单的 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);
    }
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        简而言之,不,但是如果我经常使用控件,我有一些功能可以帮助我:

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

        这样我把所有的转换都保存在一个地方,不用担心像y - this.Height这样的东西分散在代码中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-23
          • 1970-01-01
          • 2022-01-23
          • 1970-01-01
          • 2011-02-11
          相关资源
          最近更新 更多