Reputation: 799
I'm following a tutorial to get the basics of dealing with a paint event using windows forms.
So far the program kind of works, but any update of the graphics is not deleting the previously drawn lines (the graphics is not being disposed of).
The original tutorial used Refresh
, but that didn't seem to work and I replaced it with Invalidate
+Update
.
Also, setting the graphics control to this.CreateGraphics()
wasn't working and I switched it to panel2.CreateGraphics()
(I also tried e.Graphics
without results).
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();
}
}
}
Upvotes: 0
Views: 440
Reputation: 799
The problem with my code was that the drawing instructions were included in the paint event for the form. By setting the drawing in the paint event for the panel and then setting the graphics to the standard paint event for it everything worked out. Also, Refresh started to work.
Upvotes: 1