Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How can i change this code in order to draw a rounded rectangle ?

C#
public partial class MikePainter : Form
{
   private Bitmap PicInMemory;
   private Graphics PaintOnMyPic;
 
   private int SecondX;   
   private int SecondY;

   public MikePainter()
   {
       InitializeComponent();

       PicInMemory = new Bitmap(panel1.Width, panel1.Height);
       Graphics PaintOnMyPic = Graphics.FromImage(PicInMemory);

///////////How to change this code to draw rounded rectangle////////////////

private void OnMouseMove(object sender, MouseEventArgs e)
{
  if (Selectedtool == Rect ) --> Check if the selectTool is rect 
  {
    Pen myPen = new Pen(Color.Black);
    Graphics PaintOnPanel = panel1.CreateGraphics();
    PaintOnPanel.DrawImage(PicInMemory, 0, 0);
    PaintOnPanel.DrawRectangle(myPen, SecondX,SecondY,e.X - SecondX,e.Y - SecondY);
  }
}

private void OnMouseUp(object sender, MouseEventArgs e)
{
  if (Selectedtool == Rect )
  {
    Graphics PaintOnPic = Graphics.FromImage(PicInMemory); 
    Pen myPen = new Pen(Color.Black);
    PaintOnPic.DrawRectangle(myPen, SecondX, SecondY, e.X - SecondX, e.Y - SecondY);
    Graphics PaintOnPanel = panel1.CreateGraphics();
    PaintOnPanel.DrawImage(PicInMemory, 0, 0);
  }
}

private void OnMouseDown(object sender, MouseEventArgs e)
{
   SecondX = e.X;
   SecondY = e.Y;
}
Posted
Updated 29-Sep-11 4:03am
v2

Firstly, stop creating Graphics objects: they are a scarce resource and will generally run out well before the Garbage Collector chips in to Dispose them. If you create a Graphics object, you should Dispose it when you hgave finished with it. The same goes for Pens, Brushes, and so forth.

Second: Instead of faffing like you are, do your painting in the panel1 Paint event - you are handed the appropriate Graphics object ready to go in the EventArgs parameter, and it means that you picture is drawn when ever it needs to be. You can force it by using the Invalidate method of the panel, which will cause a re-draw when ready.

Thirdly, see this article: Extended Graphics - Rounded rectangles, Font metrics and more for C# 3.0[^]
 
Share this answer
 
See here for instance: http://www.gutgames.com/post/Drawing-a-Box-With-Rounded-Corners-in-C.aspx[^]. Here you'll find a CP homegrown solution: Extended Graphics[^].

And on MSDN we find out how to do this natively: http://msdn.microsoft.com/en-us/library/system.drawing.rectangle.round.aspx[^] in .NET.

Enjoy!

Best Regards,

—MRB
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900