在PictureBox中绘制线条

时间:2011-06-05 14:32:23

标签: c# graphics drawing gdi+ picturebox

首先,我需要在加载到PictureBox控件中的单色输入图像上制作一些彩色涂鸦(下图来自M. Yang文章的静态图像着色)。

Enter image description here

我正在尝试使用它来获得效果:

private void PictureBoxOnMouseDown(Object sender, MouseEventArgs e)
{
    if((e.Button & MouseButtons.Left) == MouseButtons.Left)
    {
        this.MouseInitialPosition = e.Location;
    }
}

private void PictureBoxOnMouseMove(Object sender, MouseEventArgs e)
{
    if((e.Button & MouseButtons.Left) == MouseButtons.Left)
    {
        this.MouseLastPosition = e.Location;
    }
    this._PictureBox.Invalidate();
}

private void PictureBoxOnPaint(Object sender, PaintEventArgs e)
{
    using(var pen = new Pen(Color.Red, 3.0F))
    {
        e.Graphics.DrawLine(pen, this.MouseInitialPosition, this.MouseLastPosition);
    }
}

但那并不能让我一直在等待:

  • 我不能放几行。不存储行;

  • 我用线覆盖行;

二。我需要从我正在绘制的图像中获取所有像素并以某种方式过滤它们(即提取特殊的像素)。如何将线条/涂鸦存储到图像上,然后有效地读取图像?

2 个答案:

答案 0 :(得分:2)

一个简单的解决方案是在picturebox控件上发生mouseMove事件时存储行,然后无效重绘:

public class Lines
{
    public Point startPoint = new Point();
    public Point endPoint = new Point();
}

Lines l = new Lines();
List<Lines> allLines = new List<Lines>();

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    // Collect endPoint when mouse moved
    if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
    {
        l.endPoint = e.Location;
        //Line completed
        allLines.Add(l);
        this.pictureBox1.Invalidate();
    }
}

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    // Collect startPoint when left mouse clicked
    if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
    {
        l = new Lines();
        l.startPoint = e.Location;
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    foreach (var aLine in allLines)
    {
        e.Graphics.DrawLine(Pens.Blue, aLine.startPoint, aLine.endPoint);
    }
}

答案 1 :(得分:1)

只需保留一系列行。然后当调用OnPaint时绘制所有行。

Line类将类似于:

public class Line
{
    public List<Point> Points = new List<Point>();

    public DrawLine(Pen pen, Grphics g)
    {
        for (int i = 0; i < Points.Count - 1; ++i)
            g.DrawLine(pen, Points[i], Points[i+1];
    }
}

private void PictureBoxOnMouseDown(Object sender, MouseEventArgs e)
{
    if((e.Button & MouseButtons.Left) == MouseButtons.Left)
    {
        var newLine = new Line();
        newLine.Points.Add(e.Location);
        lines.Add(newLine);
    }
}

PictureBoxOnMouseMove(Object sender, MouseEventArgs e)
{
    if((e.Button & MouseButtons.Left) == MouseButtons.Left)
    {
        lines[lines.Count-1].Points.Add(e.Location);
    }
}

private void PictureBoxOnPaint(Object sender, PaintEventArgs e)
{
    using(var pen = new Pen(Color.Red, 3.0F))
    {
        foreach (var line in lines)
            DrawLine(pen, e.Graphics)
    }
 }