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);
    }
}
相關文章
相關標籤/搜索