如果您想考虑所有可能的选项(实际高度/宽度大于/小于虚拟高度/宽度)并确保提供最佳配置(重新缩放以使可用空间最大化),则不是如此简单。下面的代码说明了所有的可能性:
double safeRatio = 0.95; //Avoiding identical height/width
double heightWidthRatio = virtualRectHeight / virtualRectWidth; //450 / 300
double diffWidth = safeRatio * realRectWidth - virtualRectWidth;
double diffHeight = safeRatio * realRectHeight - virtualRectHeight;
double virtualRectWidth_final = virtualRectWidth;
double virtualRectHeight_final = virtualRectHeight;
if (diffWidth <= 0 && diffHeight <= 0) //virtualRectWidth >= safeRatio*realRectWidth and virtualRectHeight >= safeRatio*realRectHeight
{
int counterDec = 10;
if(Math.Abs(diffWidth) > Math.Abs(diffHeight))
{
virtualRectWidth_final = safeRatio * realRectWidth + counterDec;
do
{
virtualRectWidth_final = safeRatio * realRectWidth - counterDec;
virtualRectHeight_final = virtualRectWidth_final * heightWidthRatio;
} while(virtualRectHeight_final > safeRatio * realRectHeight);
}
else
{
virtualRectHeight_final = safeRatio * realRectHeight + counterDec;
do
{
virtualRectHeight_final = safeRatio * realRectHeight - counterDec;
virtualRectWidth_final = virtualRectHeight_final / heightWidthRatio;
} while(virtualRectWidth_final > safeRatio * realRectWidth);
}
}
else if (diffWidth <= 0) //virtualRectWidth >= safeRatio*realRectWidth
{
virtualRectWidth_final = safeRatio * realRectWidth;
virtualRectHeight_final = virtualRectWidth_final * heightWidthRatio;
if (virtualRectHeight_final >= safeRatio * realRectHeight)
{
virtualRectHeight_final = safeRatio * realRectHeight;
virtualRectWidth_final = virtualRectHeight_final / heightWidthRatio;
}
}
else if (diffHeight <= 0) //virtualRectHeight >= safeRatio*realRectHeight
{
virtualRectHeight_final = safeRatio * realRectHeight;
virtualRectWidth_final = virtualRectHeight_final / heightWidthRatio;
if (virtualRectWidth_final >= safeRatio * realRectWidth)
{
virtualRectWidth_final = safeRatio * realRectWidth;
virtualRectHeight_final = virtualRectWidth_final * heightWidthRatio;
}
}
else //virtualRectWidth < safeRatio*realRectWidth && virtualRectHeight < safeRatio*realRectHeight
{
if (diffWidth < diffHeight)
{
virtualRectHeight_final = virtualRectWidth_final * heightWidthRatio;
}
else
{
virtualRectWidth_final = virtualRectHeight_final / heightWidthRatio;
}
}
最终值由virtualRectWidth_final
和给出virtualRectHeight_final
。通过一些工作,您可能会减小代码的大小,但这里重要的是结果,而且......我已经做了足够的工作来回答您的问题。