Transforming coordinates of one rectangle to another rectangle

前端 未结 3 446
予麋鹿
予麋鹿 2021-01-12 20:29

\"enter

in the above image I have shown two rectangles

  • rectangl
3条回答
  •  孤独总比滥情好
    2021-01-12 21:21

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

提交回复
热议问题