【问题标题】:Make +y UP, Move Origin C# System.Drawing.GraphicsMake +y UP,移动原点 C# System.Drawing.Graphics
【发布时间】:2012-01-31 22:59:40
【问题描述】:

我希望原点位于窗口的中心。

______________ | ^ | | | | | o----->| | | |____________|

.NET 希望它位于左上角。

_____________> | | | | | | | | V____________|

Dot net 和我正在努力相处..

有谁知道如何在 C# 中仅使用 Graphics 对象来做到这一点?

Graphics.TranslateTransform 不会这样做,因为它会使坐标倒置。结合此 Graphics.ScaleTransform(1,-1) 也不能令人满意,因为这会使文本看起来颠倒。

【问题讨论】:

    标签: c# drawing system.drawing


    【解决方案1】:

    一种解决方案是使用 TranslateTransform 属性。然后,您可以创建自己的 FlippedPoint/FlippedPointF 结构,而不是使用 Point/PointF 结构,这些结构具有对 Point/PointF 的隐式转换(但通过转换它们,坐标会被翻转):

    public struct FlippedPoint
    {
        public int X { get; set; }
        public int Y { get; set; }
    
        public FlippedPoint(int x, int y) : this()
        { X = x; Y = y; }
    
        public static implicit operator Point(FlippedPoint point)
        { return new Point(-point.X, -point.Y); }
    
        public static implicit operator FlippedPoint(Point point)
        { return new FlippedPoint(-point.X, -point.Y); }
    }
    

    【讨论】:

      【解决方案2】:

      您可以继续使用ScaleTransform(1, -1) 并在绘制文本时暂时重置当前转换:

      // Convert the text alignment point (x, y) to pixel coordinates
      PointF[] pt = new PointF[] { new PointF(x, y) };
      graphics.TransformPoints(CoordinateSpace.Device, CoordinateSpace.World, pt);
      
      // Revert transformation to identity while drawing text
      Matrix oldMatrix = graphics.Transform;
      graphics.ResetTransform();
      
      // Draw in pixel coordinates
      graphics.DrawString(text, font, brush, pt[0]);
      
      // Restore old transformation
      graphics.Transform = oldMatrix;
      

      【讨论】:

        【解决方案3】:

        尝试创建具有负高度的图形对象。我不知道具体的 C# 库,但这个技巧适用于最新版本的 GDI。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多