C# - WInForms - 在重绘事件中处理旧图形

时间:2016-05-27 14:33:55

标签: c# winforms graphics gdi+

我按照教程来了解使用Windows窗体处理绘图事件的基础知识。

到目前为止,该程序有点工作,但任何图形更新都不会删除以前绘制的线条(图形没有被处理掉)。

原始教程使用了Refresh,但这似乎无效,我将其替换为Invalidate + Update

此外,将图形控件设置为this.CreateGraphics()并不起作用,我将其切换为panel2.CreateGraphics()(我也尝试e.Graphics没有结果)。

namespace GraphicsTutorialV1
{
    public partial class Form1 : Form
    {
        Pen myPen = new Pen(Color.Black);
        Graphics g = null;

        static int start_x, start_y;
        static int end_x, end_y;

        static int my_angle = 0;
        static int my_length = 0;
        static int my_increment = 0;
        static int num_lines = 0;

        public Form1()
        {
            InitializeComponent();

            Int32.TryParse(textBox1.Text, out num_lines);
            Int32.TryParse(textBox2.Text, out my_angle);
            Int32.TryParse(textBox3.Text, out my_length);
            Int32.TryParse(textBox4.Text, out my_increment);

            start_x = (panel2.Width / 2);
            start_y = (panel2.Height / 2);
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            myPen.Width = 1;
            g = panel2.CreateGraphics();
            //g = e.Graphics;

            for(int i = 0; i < num_lines; i++)
            {
                drawLine();
            }
        }

        private void drawLine()
        {
            int temp;
            Int32.TryParse(textBox2.Text, out temp);
            my_angle = my_angle + temp;
            Int32.TryParse(textBox4.Text, out temp);
            my_length = my_length + temp;

            end_x = (int)(start_x + Math.Cos(my_angle * Math.PI / 180) * my_length);
            end_y = (int)(start_y + Math.Sin(my_angle * Math.PI / 180) * my_length);

            Point[] points =
            {
                new Point(start_x, start_y),
                new Point(end_x, end_y)
            };

            start_x = end_x;
            start_y = end_y;

            g.DrawLines(myPen, points);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Int32.TryParse(textBox1.Text, out num_lines);
            Int32.TryParse(textBox2.Text, out my_angle);
            Int32.TryParse(textBox3.Text, out my_length);
            Int32.TryParse(textBox4.Text, out my_increment);

            this.Invalidate();
            this.Update();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我的代码的问题是绘图说明包含在表单的paint事件中。通过在面板的paint事件中设置绘图,然后将图形设置为标准绘制事件,一切都解决了。此外,刷新开始工作。