boundingBoxPreservingAspectRatioXmidYmid method
Box is interpreted as a proportion, with 100 being the highest unit value.
- Tip: Set the aspect ratio of this Rect before calling this method,
- which is done by setting the height to 1.0 and the width to the aspect ratio.
Implementation
void boundingBoxPreservingAspectRatioXmidYmid(Box box, Rect rect)
{
double aspectRatioBefore = toSize().aspectRatio();
// Compute size based on box which will contain rect within space defined by box.
width = (rect.width * 100.0) / (100.0 - (box.left + box.right) );
height = (rect.height * 100.0) / (100.0 - (box.top + box.bottom) );
// Initial position.
left = rect.left;
top = rect.top;
// Compute position from box such that box contains rect.
left -= (box.left/100.0) * width;
top -= (box.top/100.0) * height;
// Correction for aspect ratio. This is necessary because we may be given Box.ZERO_BOX, which won't match aspect ratio.
// We must gracefully handle this so we can get a good initial state.
double aspectRatio = toSize().aspectRatio();
if (aspectRatio > aspectRatioBefore) {
double oldHeight = height;
height = width * (1/aspectRatioBefore);
// Adjust position so as to center (XmidYMid).
top -= 0.5 * ( (height - oldHeight) / height ) * height;
}
else if (aspectRatio < aspectRatioBefore) {
double oldWidth = width;
width = height * aspectRatioBefore;
// Adjust position so as to center (XmidYMid).
left -= 0.5 * ( (width - oldWidth) / width ) * width;
}
}