简体   繁体   中英

Drawing shapes in a panel

hope you can help me. I have to draw some shapes into a panel like a ellipse, circle, square etc.. this is my code:

private void Form1_Load(object sender, EventArgs e)
{
    pnForm.BackColor = Color.White;
    Graphics g = pnForm.CreateGraphics();
    HatchBrush hb = new HatchBrush(HatchStyle.BackwardDiagonal, Color.Black, Color.White);

    if (rbQuadrat.Checked == true)
    {
       g.FillRectangle(hb, 10, 10, 50, 50);
    }
}

I set radiobuttons to choose between the shapes, but when I check the square, nothing appears in the panel. I tried various parameters like pnForm.ClientRectangle.Width/Height, other number values etc but nothing worked for me.

PS. It's not the "pnForm.Backcolor = Color.White", I tested it without this code and it doens't work either.

EDIT: I deleted the if clause and now it's working. Let you know when I found my mistake.

Judging from the name of the method, your code is invoked only once on form load. Windows Forms/GDI is a stateless drawing architecture. It does not know that it should repaint the application if the checkbox's value changes.

Instead do something like in this answer and make sure to Invalidate() the panel you are rendering into whenever the state of your checkbox changes.

Instead of using the Form_Load event, you should code the radioButton_CheckedChanged . So, if you can handle right some if statements, you can draw rectangles, squares and so on when this event is fired. For instance:

private void radioButton1_CheckedChanged(sender, e) {
  if(radioButton1.Checked) {
      pnForm.Invalidate(); // or pnForm.Refresh();
      //Draw shape1
  }
}
private void radioButton2_CheckedChanged(sender, e) {
  if(radioButton2.Checked) {
     pnForm.Invalidate(); // or pnForm.Refresh();
     //Draw shape2
  }
}

and so on. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM