在PictureBox上绘制线条

时间:2010-11-24 12:27:40

标签: c# .net graphics line picturebox

我的问题与Stack Overflow问题 Draw lines on a picturebox using mouse clicks in C# 有关,但当鼠标按钮启动时,绘制的线条会消失。我该如何解决这个问题?

private void GainBox_MouseDn(object sender, MouseEventArgs e)
{
    mouse_dn = true;
}

private void GainBox_MouseMv(object sender, MouseEventArgs e)
{
    //Line drawn from lookup table
    if (mouse_dn)
    {
        img = new Bitmap(256, 256);

        //Get the coordinates (x, y) for line from lookup table.

        for (x = x1; x < x2; x++)
            img.SetPixel(x, y, Color.Red);

        //Same for y coordinate
    }
    GainBox.Refresh();
}

private void GainBox_MouseUp(object sender, MouseEventArgs e)
{
    mouse_dn = false;
}

3 个答案:

答案 0 :(得分:1)

这是一个小的完整程序,它根据点绘制线条(在这种情况下,它跟随鼠标)。我认为你可以根据自己的需要进行修改。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }


    // Variable that will hold the point from which to draw the next line
    Point latestPoint;


    private void GainBox_MouseDown(object sender, MouseEventArgs e)
    {
        if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
        {
            // Remember the location where the button was pressed
            latestPoint = e.Location;
        }
    }

    private void GainBox_MouseMove(object sender, MouseEventArgs e)
    {
        if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
        {
            using (Graphics g = GainBox.CreateGraphics())
            {
                // Draw next line and...
                g.DrawLine(Pens.Red, latestPoint, e.Location);

                // ... Remember the location
                latestPoint = e.Location;
            }
        }
    }
}

您的解决方案中的一个问题是您正在绘制临时位图,但该位图中的图像永远不会传输到您的PictureBox。在此处提供的解决方案中,不需要任何额外的位图。

答案 1 :(得分:0)

gainbox.refresh()应该留在if (mouse_dn)条款中。

答案 2 :(得分:0)

使用图形对象绘制线条

e.g。

Graphics gfx = GainBox.CreateGraphics();
gfx.Drawline([Your Parameters here]);