在PictureBox上画线

4

我的问题与 Stack Overflow 的这个问题 在 C# 中使用鼠标单击在 picturebox 上绘制线条 相关,但当鼠标按钮松开后,绘制的线条会消失。我该如何解决这个问题?

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;
}

1
请不要在问题标题中包含有关所使用编程语言的信息,除非没有它就没有意义。标签可以起到这个作用。 - Ondrej Janacek
如果您想在WinForm PictureBox上绘制,请参考DrawLines to DrawBeziers - Dour High Arch
3个回答

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 中。在这里提供的解决方案中,不需要任何额外的位图。

@Fedrick:你在谈论手绘...但我想改变现有曲线的形状...当我在图片框上点击某个位置时,曲线应通过该点...(玩弄图像的输入输出曲线...) - Dark Knight
@Sisya:我的回答中重要的不是如何获取点,而是如何进行绘图。 - Fredrik Mörk
@Fedrick:是的...实际上我想拖动(而不是绘制)线条覆盖整个图片框,就像Photoshop中的[图像->调整->曲线]。 - Dark Knight
@Sisya:如果你保留了一个列表,其中包含代表你的形状的Point值(或x,y对),那么你可以轻松地遍历它,使用我的代码从0到1、1到2、...、n-0绘制形状。如果你的问题实际上是关于拖动点(例如检测应该拖动哪个点,保持点列表最新等),那就是完全不同的问题了。 - Fredrik Mörk
抱歉,这是我的错误。它正在拖动,而且在拖动后,当鼠标弹起事件发生时,应该在该位置绘制一个小圆圈或点。 - Dark Knight
那段代码绘制到一个Graphics上下文中,该上下文很快就会被处理并且不会持久存在。如果你想在屏幕上保留这条线,你需要在Paint事件处理程序中绘制,而不是在MouseMoved中。 - Dour High Arch

0

gainbox.refresh() 应该留在 if (mouse_dn) 子句内。


0
使用图形对象绘制线条
例如:
Graphics gfx = GainBox.CreateGraphics();
gfx.Drawline([Your Parameters here]);

这将在本地“Graphics”上绘制线条,该图形很快就会超出范围,而不是在屏幕上显示。 - Dour High Arch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接