Friday, November 17, 2006

Create Rounded Rectangle .NET GDI+

This is based on the article published by Robbe D. Morris.



I have just corrected his publishing which could have been done in haste. The rounded rectangles do keep the width and the height specified while drawing and I have also removed the extra rectangle that is needed by using one of the path properties.



The width and the height could also be obtained by the text size that needs to be present inside the rectangle. As its done below and then adding the necessary padding required.



g.MeasureString(buttonText, buttonTextFont);



Here is the code to draw the rectangle



private void CreateRoundedRectangle(Graphics g)
{
try
{
Size cornerSize = new Size(10, 10);

// Define the starting point from the control to which to draw.
int x = 5;
int y = 5;



// Set positions for the arcs and center positions for the rectangle

int w = 200;
int h = 200;


//this is cause the width and height is calculated
//with a pensize of 1 already drawn
//you need to adjust this if you are using a pensize
//greater than 1
w--;
h--;


int xr = w + x - cornerSize.Width;
int yr = h + y - cornerSize.Height;



//create 4 rounded rectangles
Rectangle tl = new Rectangle(x , y, cornerSize.Width, cornerSize.Height);
Rectangle tr = new Rectangle(xr, y, cornerSize.Width, cornerSize.Height);
Rectangle br = new Rectangle(xr, yr, cornerSize.Width, cornerSize.Height);
Rectangle bl = new Rectangle(x, yr, cornerSize.Width, cornerSize.Height);

//its enough to add the arc present by the four rectangles
//and the path would be completed automatically.
//The rectangles would have to be added in order.
//top left, top right, bottom right, bottom left.
//this order can have any one of the rectangles as start rectangle.

//Since we are using the startfigure the completion of joing the bl
//with tl rectangle is done automatically.

// Standard angle for each arc.
float sweepAngle = 90.0f;


GraphicsPath path = new GraphicsPath();

path.StartFigure();
path.AddArc(tl, 180, sweepAngle);
path.AddArc(tr, 270, sweepAngle);
path.AddArc(br, 360, sweepAngle);
path.AddArc(bl, 90, sweepAngle);
path.CloseFigure();



// Create pen.
Pen blackPen = new Pen(Color.Black, 1);

// Draw graphics path to screen.
g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawPath(blackPen, path);
//fill the path
g.FillPath(Brushes.LightBlue, path);

//clean up
path.Dispose();
blackPen.Dispose();
}
catch (Exception ex)
{
throw;
}

}


Happy programming