我有一个桌面应用程序,显示用户屏幕的虚拟表示。我的应用程序中画布的比例与用户屏幕的比例不匹配。
在我的应用程序中,用户可以在屏幕上添加矩形部分。添加矩形后,实际桌面上的默认大小为450x300。所以我需要调整虚拟桌面中的矩形以反映它。
所以我不能简单地这样做:
double virtualRectWidth = VirtualResolutionX / (RealResolutionX / 450);
double virtualRectHeight = virtualRectWidth / (RealResolutionX / RealResolutionY);
宽高比不匹配。
如何调整虚拟矩形的大小?
答案 0 :(得分:1)
如果您要考虑所有可能的选项(实际高度/宽度大于/小于虚拟高度/宽度)并确保提供最佳配置(重新缩放以使可用空间最大化),它不是那么简单。以下代码说明了所有可能性:
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
给出。通过一些工作,你可能会减少代码的大小,但重要的是结果,而且......我已经做了足够的工作来回答你的问题。