将一个矩形的坐标转换为另一个矩形

将一个矩形的坐标转换为另一个矩形

本文介绍了将一个矩形的坐标转换为另一个矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在上面的图片我已经显示了两个矩形




  • 矩形1 ,其中x可以从-900到13700变化,Y可以从-600到6458

  • rectangle 2 ,它的坐标X可以从0到3000变化,y可以从0到2000不等。


另外: rectangle 2 的起点位于左上方位置(0,0),矩形1 具有起点(宽度/ 2,高度/ 2)。

我需要做什么:要转换矩形1 指向矩形2 使用缩放或平移的点

所以,应该按比例缩放为了将 rectangle 1 的坐标转换为 的坐标系, x 和 y em> rectangle 2

解决方案

如果:

 对于宽度和高度,矩形1有(x1,y1)原点和(w1,h1),
矩形2有(x2,y2)原点和(w2,h2)为宽度和高度,则

根据矩形1坐标给定点(x,y),将其转换为矩形2坐标:

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

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





在C#中,上面的内容看起来像这样:

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


in the above image I have shown two rectangles

  • rectangle 1 whose x can vary from -900 to 13700 and Y can vary from -600 to 6458
  • rectangle 2 whose coordinate X can vary from 0 to 3000 and y can vary from 0 to 2000

Also: rectangle 2 has its starting point at left top position(0,0) whereas rectangle 1 has starting point( width/2, height/2).

What I need to do: to convert a point of rectangle 1 to point of rectangle 2 using scaling or translation.

So, what should be scaling factor for x and y coordinates in order to transform the coordinate of rectangle 1 to rectangle 2?

解决方案

If:

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;

Do the calculation in floating point and convert back to integer after, to avoid possible overflow.


In C#, the above would look something like:

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

这篇关于将一个矩形的坐标转换为另一个矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:57