Halcon - 图像随 HWindowControl 控件缩放的同时,保持图像的长宽比例不变

背景

一般状况下,图像是填充满 HWindowControl 控件,并随其缩放的。此时只须要将 set_part 的参数设置成图像的大小便可。spa

不过,有时候,在一些测量任务中,咱们对原始图像的长宽比敏感,此时的图像显示最好是能保持图像的长宽比不变。code

正文

如何保证图像显示的长宽比例呢?答案是将 HWindowControl 控件的 ImagePart 设置成与自身控件的长宽比一致便可。这里咱们假设:io

图像的大小是 imgWidth 和 imgHeightclass

HWindowControl 控件的窗体大小是 winWidth 和 winHeight程序

HWindowControl 控件的 ImagePart 大小是 partWidth 和 partHeightim

因此,有: $$ \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# 程序:img

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);
    }
}
相关文章
相关标签/搜索