如何将正常坐标系与图像坐标系拟合?

时间:2016-07-12 20:13:20

标签: c# image coordinates

快速提问:

我有这些坐标:

enter image description here

我在Bitmap Image上绘制它们:

    foreach (var point in MyCoords)
    {
        drawingContext.DrawEllipse(null, new Pen(new SolidColorBrush(Colors.Aqua), 1), new Point(point.X+100, point.Y+100) , 1, 1); 
    }

输出:

enter image description here

为什么形状不匹配?因为位图像素y轴被翻转(0顶部和最大底部)。

修正:

    foreach (var point in MyCoords)
    {
        drawingContext.DrawEllipse(null, new Pen(new SolidColorBrush(Colors.Aqua), 1), new Point(point.X+100, (Bitmap.Height - point.Y)-100), 1, 1);
    }

输出:

enter image description here

有没有更好的方法在后面的代码中处理我的坐标系,然后“正确”显示它?

2 个答案:

答案 0 :(得分:2)

您应该可以将Transform应用于Graphics实例,该实例将在绘制点时对其进行修改。

这样的东西应该有效,因为它会翻转Y轴:

drawingContext.ScaleTransform( 1.0f, -1.0f, MatrixOrder.Prepend );

通过评论,您实际上似乎在使用DrawingContext实例而不是Graphics。试试这个:

drawingContext.PushTransform(new ScaleTransform(0.0f, -1.0f));

Graphics类上的方法不同,DrawingContext使用Transforms堆栈,因此您需要确保只应用一次DrawingContext。您可能还需要使用ScaleTransform构造函数的其他重载之一来将图像的大小计入帐户(CenterXCenterY)。

答案 1 :(得分:1)

基于GDI + Calls的System.Graphics例程“继承”烘焙到Windows中的坐标系。这是一个纯粹的定义问题。无法配置自己的系统。另一种思考方式是定义一组绘图操作并应用整个集合的变换(这种方法在基于矢量的图形库中更常见)。所以至少你可以把坐标转换的代码放在一个地方(如果在整个代码库中重复new Point(point.X+100, (Bitmap.Height - point.Y)-100),那就太可怕了)。什么是扩展方法:

public static class PointExtensions
{
    public static Point ToSystem(this Point point, Bitmap bitmap)
    {
        return new Point(point.X + 100, bitmap.Height - point.Y - 100);
    }
}

这将导致更易读的代码:

   foreach (var point in MyCoords)
    {
        drawingContext.DrawEllipse(
              null, 
              new Pen(new SolidColorBrush(Colors.Aqua), 1),                
              point.ToSystem(bitmap),  /// <- better to read
              1, 1);
    }