1

I would like to take a convex polygon and fit it into a given rectangle by turning and scaling.

My approach is to turn the polygon in small steps (like 1°) and always measure the fraction (maximal horizontal distance / maximal vertical distance), take the one that is nearest to fraction (rectangle width / rectangle height) and scale it to fit into the rectangle.

I wonder whether there is a "less primitive" approach. Furthermore there might be a better definition of "best fit" than just measuring maximal horizontal and vertical distance. My real aim is to make the polygon "look good", when I store it an image file or print it on a page.

Frank Puffer
  • 8,135
  • 2
  • 20
  • 45
J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
  • Intuitively, it seems like you should just try aligning each edge of the polygon in turn with one of the sides of your rectangle, do a bounding box calculation, and see which rotation fits your rectangle best. That should "look good" because people will see your polygon edge aligning with your rectangle nicely and feel nice. – samgak Jun 25 '16 at 11:55

1 Answers1

3

You can use method like rotating calipers. enter image description here

While rotating calipers algorithm finds pairs of antipodal vertices with two parallel lines, you need four perpendicular lines - bounding rectangle.

Choose the first vertice, find antipodal vertice for it - it is the first caliper pair.
Build the second caliper pair perpendicular to the first one.
Rotate both caliper pairs together until then next antipodal pair is found (either between first calipers, or between second ones) - you determine the next extremal angle point.
Continue to rotate calipers.

Both width and height of bounding rectangle will vary continuously between extremal points. And width/height proportion will continuous too. So if you find that in i-th extremal point W/H < P and in (i+1)-th extremal point W/H > P, where P is needed proportion, then interval i..i+1 contains needed P value (Bolzano's theorem).

When you found interval with solution (if exists), just calculate proportion of caliper widths at this angle interval (trigonometric equation) and get exact angle value. Trigonometric equation seems look as

Sin(A) / Sin(A + Pi/2) = F   
or
Sin(A) / Cos(A) = Tan(A) = F
MBo
  • 77,366
  • 5
  • 53
  • 86