Last active
August 5, 2018 22:21
-
-
Save GuiRitter/aee01e7790e75c4b29460c9efeaac52d to your computer and use it in GitHub Desktop.
Code to fit a rectangle inside another rectangle while keeping aspect ratio.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class FitRectangleInRectangle { | |
public static class Input { | |
public int height; | |
public int width; | |
public Input() {} | |
public Input(int width, int height) { | |
this.width = width; | |
this.height = height; | |
} | |
} | |
public static class Output extends Input { | |
public double scale; | |
@Override | |
public String toString() { | |
return String.format("{width: %s, height: %s, scale: %s}", | |
width, height, scale); | |
} | |
public Output() {} | |
public Output(int width, int height, double scale) { | |
super(width, height); | |
this.scale = scale; | |
} | |
} | |
public static final Output fitRectangleInRectangle(Input inner, Input outer) { | |
Output output = new Output(); | |
if ((inner == null) || (outer == null)) { | |
return null; | |
} | |
double innerAspectRatio = ((double) inner.width) / ((double) inner.height); | |
double outerAspectRatio = ((double) outer.width) / ((double) outer.height); | |
if (innerAspectRatio < outerAspectRatio) { | |
output.scale = ((double) outer.height) / ((double) inner.height); | |
} else { | |
output.scale = ((double) outer.width) / ((double) inner.width); | |
} | |
output.width = (int) Math.round(output.scale * ((double) inner.width )); | |
output.height = (int) Math.round(output.scale * ((double) inner.height)); | |
return output; | |
} | |
public static void main(String[] args) { | |
System.out.println(fitRectangleInRectangle(new Input(500, 250), new Input(200, 50))); | |
System.out.println(fitRectangleInRectangle(new Input(250, 200), new Input(200, 50))); | |
} | |
} | |
/* | |
TODO permute possibilites to make test cases | |
ratio inner ? outer | |
< | |
= | |
> | |
size inner ? outer (completely contain or be contained to make it easier at first) | |
< | |
= | |
> | |
inner aspect ratio | |
horizontal | |
square | |
vertical | |
outer aspect ratio | |
horizontal | |
square | |
vertical | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment