【问题标题】:C# Draw on PictureBox with Graphics.DrawLine() not working on Paint eventC# 在带有 Graphics.DrawLine() 的 PictureBox 上绘制不适用于 Paint 事件
【发布时间】:2021-12-03 10:55:26
【问题描述】:

我有一个带有 PictureBox 和一个按钮的 from(见图)。

当用户点击“绘制”时,程序会绘制两个十字。

我为 PictureBox Paint 事件处理程序做了同样的事情,但如果我最小化表单并重新打开它,则不会绘制任何内容(除了图片框的 Image 属性):

代码:

 public partial class Form1 : Form
{

    Point[] points = new Point[2];
    Graphics g;
    public Form1()
    {
        InitializeComponent();
        points[0] = new Point(50, 50);
        points[1] = new Point(100, 100);
        g = pictureBox1.CreateGraphics();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DrawCrosses(points);
    }

    private void DrawCrosses(Point[] points)
    {
        
        Pen pen = new Pen(Color.Red)
        {
            Width = 2
        };
        foreach (Point p in points)
        {
            Point pt1 = new Point(p.X, p.Y - 10);
            Point pt2 = new Point(p.X, p.Y + 10);
            Point pt3 = new Point(p.X - 10, p.Y);
            Point pt4 = new Point(p.X + 10, p.Y);
            g.DrawLine(pen, pt1, pt2);
            g.DrawLine(pen, pt3, pt4);
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        DrawCrosses(points);
    }
}

【问题讨论】:

    标签: c# winforms graphics drawing picturebox


    【解决方案1】:

    您不应在事件处理程序中创建新的 Graphics 对象。

    你应该使用从事件传递的那个

    public partial class Form1 : Form
    {
        Point[] points = new Point[2];
        public Form1()
        {
            InitializeComponent();
            points[0] = new Point(50, 50);
            points[1] = new Point(100, 100);
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            DrawCrosses(points, pictureBox1.CreateGraphics());
        }
    
        private void DrawCrosses(Point[] points, Graphics g)
        {
    
            Pen pen = new Pen(Color.Red)
            {
                Width = 2
            };
            foreach (Point p in points)
            {
                Point pt1 = new Point(p.X, p.Y - 10);
                Point pt2 = new Point(p.X, p.Y + 10);
                Point pt3 = new Point(p.X - 10, p.Y);
                Point pt4 = new Point(p.X + 10, p.Y);
                g.DrawLine(pen, pt1, pt2);
                g.DrawLine(pen, pt3, pt4);
            }
        }
    
        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            DrawCrosses(points, e.Graphics);
        }
    }
    

    【讨论】:

    • 如果您希望按钮“绘制”十字架,我仍然会使用Paint() 事件及其提供的e.Graphics。在表单级别创建一个布尔变量 (bool),用于确定十字是否可见。在您的绘画事件中,如果布尔值为真,您只调用DrawCrosses()。在 Button 处理程序中,您只需将 Boolean 设置为 true,然后告诉 PictureBox 用pictureBox1.Refresh(); 重新绘制自己。同样,您可以通过将布尔值设置为 false 并再次刷新来关闭十字。
    猜你喜欢
    • 2015-04-22
    • 2015-04-23
    • 2016-12-12
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    相关资源
    最近更新 更多