在图片框中的现有图像上画线 [英] Draw lines over existing image in picture box

查看:57
本文介绍了在图片框中的现有图像上画线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我想在图片框(VS2008,.net3.5)中的现有图像上绘制线条.就绘制一次而言,没有任何问题.但是,我希望在图片框内移动时将这些行移动到鼠标位置.所以我在PictureBox_MouseMove事件中编写了以下代码:-

Hi all,
I want to draw lines over an existing image in a picturebox (VS2008, .net3.5). No issues as far as drawing it once is concerned. But I want these lines to be shifted to the mouse position as I move in the picture box. So I wrote the following code in the PictureBox_MouseMove event:-

Graphics g = pictureBox1.CreateGraphics();
            g.Clear(Color.Transparent);
            Pen p = new Pen(Color.Red, 2.0f);

            for (int n = 1; n <= 50; n++)
            {
                g.DrawLine(p, n * (Cursor.Position.X), Cursor.Position.Y - 30.0f, n * (Cursor.Position.X), Cursor.Position.Y + 30.0f);

            }


当PictureBox中没有图像时,该代码可以正常工作.当图片框中有图像时,将绘制线条,但是在此之前,已删除图片框中已存在的图像(g.Clear(Color.Transparent)).
我试图将图像保留在面板中,并在Panel_MouseMove事件中运行代码,但无济于事.
如何在保持现有图像完好无损的同时绘制这些线条?
GeoNav


The code is working fine when there is no image in the PictureBox. Whern there is an image in the picturebox, the lines are getting drawn, but before that the image already in the picturebox is getting erased (g.Clear(Color.Transparent)).
I tried to keep the image in a panel and run the code in Panel_MouseMove event, but to no avail.
How do I draw these lines while keeping the existing image intact?
GeoNav

推荐答案

首先,当您创建图形项时,您有责任销毁它.它们是(非常)有限的资源,您绝不能创建,使用它们并丢弃它们,因为整个系统都将用尽,这要早于GC为您处理它们.最好的方法是将它们放在using块中:
Firstly, when you create a graphics item, you are responsible for destroying it. They are a (very) finite resource, and you must not create them, use them and discard them as the whole system will run out, well before the GC gets round to disposing of them for you. The best way is to put them in a using block:
using(Graphics g = pictureBox1.CreateGraphics())
   {
   g.Clear(Color.Transparent);
   Pen p = new Pen(Color.Red, 2.0f);

   for (int n = 1; n <= 50; n++)
       {
       g.DrawLine(p, n * (Cursor.Position.X), Cursor.Position.Y - 30.0f, n * (Cursor.Position.X), Cursor.Position.Y + 30.0f);

       }
   }


其次,不要做你想做的事情.图片框是一种愚蠢的动物,当您手动删除它的内容时(如您在示例中所做的那样),它不知道要重新绘制它.您可以强制它重绘它的图片,但随后它将覆盖您的线条.
而是使用面板,并处理Paint事件.自己绘制图片-使用PaintEventArgs"e"的Graphics属性,这样就不必担心销毁它-然后在同一图形上下文上绘制线条.简单!


Secondly, don''t do what you are trying to do. A Picture box is a dumb animal, and when you manually erase it''s content as you do in the example you gave it doesn''t know to re-draw it. You can force it to redraw it''s picture, but then it will overwrite your lines.
Instead, use a Panel, and handle the Paint event. Draw the picture yourself - using the Graphics property of the PaintEventArgs "e" so you don''t have to worry about destroying it - then on the same graphics context draw your lines. Simples!


这篇关于在图片框中的现有图像上画线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆