背景
通常情况下,图像是填充满 HWindowControl 控件,并随其缩放的。此时只需要将 set_part
的参数设置成图像的大小即可。
不过,有时候,在一些测量任务中,我们对原始图像的长宽比敏感,此时的图像显示最好是能保持图像的长宽比不变。
正文
如何保证图像显示的长宽比例呢?答案是将 HWindowControl 控件的 ImagePart 设置成与自身控件的长宽比一致即可。这里我们假设:
图像的大小是 imgWidth 和 imgHeight
HWindowControl 控件的窗体大小是 winWidth 和 winHeight
HWindowControl 控件的 ImagePart 大小是 partWidth 和 partHeight
所以,有:
[frac{partWidth}{partHeight} = frac{winWidth}{winHeight}
]
当 winWidth < winHeight 时,我们设定 partWidth = imgWidth ,则:
[partHeight = frac{partWidth * winHeight}{winWidth} = frac{imgWidth * winHeight}{winWidth}
]
当 winWidth > winHeight 时,我们设定 partHeight = imgHeight ,则:
[partWidth = frac{partHeight * winWidth}{winHeight} = frac{imgHeight * winWidth}{winHeight}
]
C# 程序:
private void DispImage(HImage image, HWindow window)
{
int imgWidth, imgHeight, winRow, winCol, winWidth, winHeight, partWidth, partHeight;
try
{
image.GetImageSize(out imgWidth, out imgHeight);
window.GetWindowExtents(out winRow, out winCol, out winWidth, out winHeight);
if (winWidth < winHeight)
{
partWidth = imgWidth;
partHeight = imgWidth * winHeight / winWidth;
}
else
{
partWidth = imgHeight * winWidth / winHeight;
partHeight = imgHeight;
}
window.SetPart(0, 0, partHeight - 1, partWidth - 1);
window.DispImage(image);
}
catch (HalconException hEx)
{
MessageBox.Show(hEx.Message);
}
}