c# - 在 C# 中使用鼠标单击在图片框上绘制线条

标签 c# graphics line picturebox

我正在尝试制作一个程序,在 picturebox 上画线。使用鼠标单击要绘制线的起点和终点的位置。这是我当前的代码:

public partial class Form1 : Form
{
    int Drawshape;

    private Point p1, p2;
    List<Point> p1List = new List<Point>();
    List<Point> p2List = new List<Point>();

    public Form1()
    {
        InitializeComponent();
        pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Drawshape = 1;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Drawshape = 2;
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (Drawshape == 1)
        {
            if (p1.X == 0)
            {
                p1.X = e.X;
                p1.Y = e.Y;
            }
            else
            {
                p2.X = e.X;
                p2.Y = e.Y;

                p1List.Add(p1);
                p2List.Add(p2);

                Invalidate();
                p1.X = 0;
            }
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Graphics G = Graphics.FromImage(pictureBox1.Image);
        if (Drawshape == 1)
        {
            using (var p = new Pen(Color.Blue, 4))
            {
                for (int x = 0; x < p1List.Count; x++)
                {
                    G.DrawLine(p, p1List[x], p2List[x]);
                }
            }
        }
    }

目前它根本不允许我在图片框上绘图。这怎么可能?

最佳答案

Invalidate();更改为pictureBox1.Invalidate();

关于c# - 在 C# 中使用鼠标单击在图片框上绘制线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4187524/

相关文章:

linux - ubuntu中的脚本同时获取CPU温度和CPU使用率并保存到文件

c# - 从 MVC 放置/发布后如何获得 JSON 响应

c# - 编译大型 C# 解决方案? (450 万行代码)

android - 我需要了解为什么 setImageMatrix 不起作用

android - 菜单图标困惑 - 它们太大了!

css - 使用 CSS 在 <span> 标签中划线

wpf - 带填充和描边的线条

c# - HttpWebRequest 或 DownloadString >> 检索部分 HTML

c# - 从模板类转换

ios - 复数应用程序 - 使用核心图、幂图或其他绘图?