A Fitting Scale

Fitting one rectangle inside another rectangle of different proportions and/or size, in Java of course:

import java.awt.Dimension;
 
// Other stuff, like class declarations and such
 
public static Dimension fitRectInRect(Dimension src, Dimension dst) {
	Dimension result = new Dimension(dst);
	double srcRatio = src.width / (double) src.height;
	double dstRatio = dst.width / (double) dst.height;
	if (srcRatio < dstRatio) {
		result.width = (int) (dst.width * srcRatio);
	}
	else if (srcRatio > dstRatio) {
		result.height = (int) (dst.height / srcRatio);
	}
	return result;
}

This function would take two objects representing a rectangular area each. The first is the size of your original rectangle and the second is the maximum area it can occupy. The return value is the largest rectangle with the same proportions as the source that fits inside the maximum area.
Dimension is used for convenience only, any other container for a width and height can be used, like an SWT Point. The function could be modified to accept other objects or the primitive values of the width and height themselves.

Leave a Comment