【问题标题】:Transforming coordinates of one rectangle to another rectangle将一个矩形的坐标转换为另一个矩形
【发布时间】:2016-03-21 16:14:24
【问题描述】:

在上图中我展示了两个矩形

  • 矩形 1,其 x 可以在 -900 到 13700 之间变化,Y 可以在 -600 到 6458 之间变化
  • 矩形 2,其坐标 X 可以在 0 到 3000 之间变化,y 可以在 0 到 2000 之间变化

另外: 矩形 2 的起点在左上位置 (0,0),而 矩形 1 的起点为 (width/ 2, 高度/2)。

我需要做的:使用缩放或平移将 rectangle 1 的点转换为 rectangle 2 的点。

那么,xy 坐标的比例因子应该是多少才能将 rectangle 1 的坐标转换为 rectangle 2

【问题讨论】:

  • 新点是否在下一个矩形内的“相同”点上?
  • 是的,它会在同一个地方
  • 无论如何我想要点之间的相对定位
  • Rectangle1 的范围可以从 -900 到 13700 但你说的原点是 (width/2,height/2)?这种建议您在 SAME 矩形中使用 2 个单独的坐标系。您在矩形内的点是从不同的原点指定到矩形角的??

标签: c# geometry transformation computational-geometry coordinate-transformation


【解决方案1】:

如果:

Rectangle 1 has (x1, y1) origin and (w1, h1) for width and height, and
Rectangle 2 has (x2, y2) origin and (w2, h2) for width and height, then

Given point (x, y) in terms of Rectangle 1 coords, to convert it to Rectangle 2 coords:

xNew = ((x-x1)/w1)*w2 + x2;
yNew = ((y-y1)/h1)*h2 + y2;

以浮点数进行计算,然后转换回整数,以避免可能的溢出。


在 C# 中,上面的内容类似于:

PointF TransformPoint(RectangleF source, RectangleF destination, PointF point)
{
    return new PointF(
        ((point.X - source.X) / source.Width) * destination.Width + destination.X,
        ((point.Y - source.Y) / source.Height) * destination.Height + destination.Y);
}

【讨论】:

  • @Peter Duniho 感谢编辑显示 C# 示例。 (是的,我知道仅仅为了感谢而发表评论是一种违反规则的行为,但规则是为了破例而写的)
  • 有没有人使用这种方法出现舍入错误?我正在使用它,我发现有时我需要向上取整以获得正确的点,有时我需要向下取整。是否应该使用比例因子?
【解决方案2】:

试试这个:

rectangelOne.x = rectangelTwo.x + rectangelTwo.width / 2;
rectangelOne.y = rectangelTwo.y + rectangleTwo.height / 2;

如果你的 rectangleOne 的轴正确,它应该自动居中,否则添加:

rectangleOne.x -= rectangleOne.width / 2;
rectangleTwo.y -= rectangleOne.height / 2;

希望这会有所帮助。

【讨论】:

    【解决方案3】:
    float transformValue (float x,float  A,float B, float C, float D){
    
        return C + ((x-A) * (D-C)/(B-A));
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 2020-07-31
      • 1970-01-01
      • 2011-11-24
      • 2018-12-06
      • 2020-04-03
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多