C# 在picturebox上 画roi区域

    科技2025-05-29  6

    思路: 设变量bdraw ,按下时鼠标的相对坐标 ,rect为roi的矩形大小 鼠标按下时,bdraw=true ,鼠标移动时计算rect 鼠标抬起时 bdraw=false,然后再paint中画矩形就ok

    //绘图

    private void DispWnd_picbox_Paint(object sender, PaintEventArgs e)//使用paint画矩形 { if(DispWnd_picbox.Image != null) { e.Graphics.DrawRectangle(new Pen(Color.Red, 3), m_draw_rect); } }

    //鼠标按下

    private void DispWnd_picbox_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { //m_oldPt = this.PointToClient(MousePosition); m_oldPt = e.Location; m_bDraw = true; Invalidate(); } }

    //鼠标移动

    private void DispWnd_picbox_MouseMove(object sender, MouseEventArgs e) { //m_newPt = this.PointToClient(MousePosition); m_newPt = e.Location; if(e.Button != MouseButtons.Left)//左键一直按着 { return; } if (m_bDraw) { int x = m_oldPt.X > m_newPt.X ? m_newPt.X : m_oldPt.X; int y = m_oldPt.Y > m_newPt.Y ? m_newPt.Y : m_oldPt.Y; int hight = Math.Abs(m_oldPt.X - m_newPt.X); int width = Math.Abs(m_oldPt.Y - m_newPt.Y); m_draw_rect = new Rectangle(x, y, hight, width); DispWnd_picbox.Invalidate(); } }

    //鼠标抬起

    private void DispWnd_picbox_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { //m_newPt = this.PointToClient(MousePosition); m_newPt = e.Location; m_bDraw = false; } }

    对于复杂的可以采用多个图层来操 参考:https://bbs.csdn.net/topics/280026189 这个一两个月前做过,我具体的做法就是使用3个"图层",也就是3个bitmap对象,一个是用来显示的,叫ViewBtm(就是我们看到的),一个是用来给graphics操作的,叫TempBtm,第三个是用来装载之前画的东西的,叫MidBtm,因为就像你说的,防止之前画的内容给Clear掉。

    步骤是:graphics在TempBtm上操作,MouseMove()中不断画,不断擦除,放开鼠标后,就将内容输出到ViewBtm,下次按下鼠标画是,先将ViewBtm的内容复制到MidBtm,然后又对TempBtm进行操作,松开鼠标后又将内容输出到ViewBtm。

    我可能说得不清楚,反正就是为了跟2楼差不多,但为了防止之前的内容给擦掉,你应该没此鼠标移动,那个举行和之前所画的东西都要全部输出出来。我有一个类,你有兴趣要就给我发EMAIL:minhuai.h@gmail.com。

    Processed: 0.010, SQL: 8