开始
以前用的是HWindowControl控件,显示的平移缩放都是自己处理。听说过HSmartWindowControl控件,有空看了一下,觉得比HWindowControl简单,而且AttachDrawingObjectToWindow功能不错,halcon自己维护了HDrawingObject对象,可以用鼠标移动和调整不需要写代码重绘,省心。
一,鼠标定点缩放
1,在Form上加入HSmartWindowControl控件
2,手动加上Form的滚轮处理
public Form1()
{
...
MouseWheel += Form1_MouseWheel;
...
}
//
public void Form1_MouseWheel(object sender, MouseEventArgs e)
{
//HSmartWindowControl控件的区域
Rectangle rect = hSmartWindowControl1.RectangleToScreen(hSmartWindowControl1.ClientRectangle);
//滚动时,鼠标悬停在在HSmartWindowControl控件上
if (rect.Contains(Cursor.Position))
{
//缩放
hSmartWindowControl1.HSmartWindowControl_MouseWheel(sender, e);
}
}
//显示原图
private void buttonRefresh_Click(object sender, EventArgs {
if (image != null)
{
HOperatorSet.GetImageSize(image, out HTuple Width, out HTuple Height);
hSmartWindowControl1.HalconWindow.SetPart(0, 0, Height.D - 1, Width.D - 1);
hSmartWindowControl1.HalconWindow.DispObj(image);
}
}
二,画Region
1,定义用于在HSmartWindowControl控件上显示Region的HDrawingObject实例
HDrawingObject doRoi = null;
2,建立和删除HDrawingObject
private void buttonGenRoi_Click(object sender, EventArgs e)
{
if (doRoi == null)
{
//创建一个矩形的显示实例
doRoi = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE1, 100, 100, 210, 210);
doRoi.SetDrawingObjectParams("color", "green");
//挂靠实例到HSmartWindowControl控件
hSmartWindowControl1.HalconWindow.AttachDrawingObjectToWindow(doRoi);
}
else
{
hSmartWindowControl1.HalconWindow.DetachDrawingObjectFromWindow(doRoi);//这里这句可以不要
doRoi = null;
}
}
3,HDrawingObject转Region
private void buttonFindLed_Click(object sender, EventArgs e)
{
if (doRoi != null)
{
//获取矩形参数
string[] str = { "row1", "column1", "row2", "column2" };
HTuple val = doRoi.GetDrawingObjectParams(str);
//生成ROI
HOperatorSet.GenRectangle1(out HObject roi, val[0], val[1], val[2], val[3]);
...
}
}
三,比例满窗口显示
1,代码
void showImage(HObject image)
{
if (image == null)
return;
//获取图像及显示窗口长宽
HOperatorSet.GetImageSize(image, out HTuple imgWidth, out HTuple imgHeight);
int wndWidth = hSmartWindowControl1.ClientRectangle.Width;
int wndHeight = hSmartWindowControl1.ClientRectangle.Height;
//计算比例
double scale = Math.Max(1.0*imgWidth.I / wndWidth, 1.0*imgHeight / wndHeight);
double w = wndWidth * scale;
double h = wndHeight * scale;
//居中时,Part的区域
hSmartWindowControl1.HalconWindow.SetPart(-(h-imgHeight)/2, -(w - imgWidth) / 2, imgHeight+(h- imgHeight.D)/2, imgWidth + (w - imgWidth) / 2);
//背景色
hSmartWindowControl1.HalconWindow.SetWindowParam("background_color", "blue");
hSmartWindowControl1.HalconWindow.ClearWindow();
hSmartWindowControl1.HalconWindow.DispObj(image);
//画根测试线
HOperatorSet.GenRegionLine(out HObject line, 0, 0, imgHeight, imgWidth);
hSmartWindowControl1.HalconWindow.SetColor("green");
hSmartWindowControl1.HalconWindow.DispObj(line);
}
2,示图,不同长宽比的图,都显示在窗口中部
图太大了,不知道怎么缩小 -_-!!!