我有一个关于Graphics对象的问题。我想画一条连续的线,例如MS paint。我不知道该怎么实现。我确实知道如何从鼠标位置开始一行。我在图片框上执行此操作,然后添加新的Point(e.X,e.Y)。另一行不能与路线相同,否则将看不到任何行。我无法制作另一个Point(10,10)或类似的东西。因为那样的话,它将总是从同一点创建一条线。

有谁知道如何绘制连续的线(带曲线)

它与mouse_down和mouse_up事件有关吗?我确实长期困扰这个问题。如果你们中有人有时间向我解释可行的方法,那就太好了!

提前致谢!

最佳答案

我刚刚为您实现了简单的绘画。只需创建一个新项目并将下面的代码复制到Form1.cs文件即可。代码中的注释应说明其工作原理。

public partial class Form1 : Form
{
    private Bitmap bmp; // Place to store our drawings
    private List<Point> points; // Points of currently drawing line
    private Pen pen; // Pen we will use to draw

    public Form1()
    {
        InitializeComponent();
        DoubleBuffered = true; // To avoid flickering effect

        bmp = new Bitmap(640, 480); // This is our canvas that will store drawn lines
        using (Graphics g = Graphics.FromImage(bmp))
            g.Clear(Color.White); // Let's make it white, like paper

        points = new List<Point>(); // Here we will remember the whole path
        pen = new Pen(Color.Black);

        MouseDown += OnMouseDown; // Start drawing
        MouseMove += OnMouseMove; // Drawing...
        MouseUp += OnMouseUp; // Stop drawing
        Paint += OnPaint; // Show the drawing
    }

    void OnPaint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(bmp, 0, 0); // Show what is drawn
        if (points.Count > 0)
            e.Graphics.DrawLines(pen, points.ToArray()); // Show what is currently being drawn
    }

    void OnMouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left)
            return;

        points.Clear();
        points.Add(e.Location); // Remember the first point
    }

    void OnMouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left)
            return;

        points.Add(e.Location); // Add points to path
        Invalidate(); // Force to repaint
    }

    void OnMouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left)
            return;

        SaveToBitmap(); // Save the drawn line to bitmap
        points.Clear(); // Our drawing is saved, we can clear the list of points
    }

    private void SaveToBitmap()
    {
        if (points.Count == 0)
            return;

        using (Graphics g = Graphics.FromImage(bmp))
            g.DrawLines(pen, points.ToArray()); // Just draw current line on bitmap
    }
}


结果:

关于c# - 在Winforms C#上的MS Paint之类的表格上绘制连续线条,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28650588/

10-12 07:40
查看更多