How to draw a rounded rectangle
The trick here is to use a GraphicsPath object to assemble a collection of lines and arcs that make up the rounded rectangle shape.
Arcs are used to round off the corners, so you have to position the lines 1 radius, whatever that may be, from the actual corner.
The routine to accomplish this is shown here in C# and VB.NET.
[C#]
public void DrawRoundRect(Graphics g, Pen p, float X, float Y, float width, float height, float radius)
{
GraphicsPath gp=new GraphicsPath();
gp.AddLine(X + radius, Y, X + width - (radius*2), Y);
gp.AddArc(X + width - (radius*2), Y, radius*2, radius*2, 270, 90);
gp.AddLine(X + width, Y + radius, X + width, Y + height - (radius*2));
gp.AddArc(X + width - (radius*2), Y + height - (radius*2), radius*2, radius*2,0,90);
gp.AddLine(X + width - (radius*2), Y + height, X + radius, Y + height);
gp.AddArc(X, Y + height - (radius*2), radius*2, radius*2, 90, 90);
gp.AddLine(X, Y + height - (radius*2), X, Y + radius);
gp.AddArc(X, Y, radius*2, radius*2, 180, 90);
gp.CloseFigure();
g.DrawPath(p, gp); gp.Dispose(); }
[VB]
Public Function DrawRoundRect(ByVal g As Graphics, ByVal p As Pen, ByVal x As Single, ByVal y As Single, ByVal width As Single, ByVal height As Single, ByVal radius As Single) Dim gp As GraphicsPath = New GraphicsPath()
gp.AddLine(X + radius, Y, X + width - (radius*2), Y);
gp.AddArc(X + width - (radius*2), Y, radius*2, radius*2, 270, 90);
gp.AddLine(X + width, Y + radius, X + width, Y + height - (radius*2));
gp.AddArc(X + width - (radius*2), Y + height - (radius*2), radius*2, radius*2,0,90);
gp.AddLine(X + width - (radius*2), Y + height, X + radius, Y + height);
gp.AddArc(X, Y + height - (radius*2), radius*2, radius*2, 90, 90);
gp.AddLine(X, Y + height - (radius*2), X, Y + radius);
gp.AddArc(X, Y, radius*2, radius*2, 180, 90);
gp.CloseFigure()
g.DrawPath(p, gp)
gp.Dispose() End Function
Back to the GDI+ FAQ
Copyright � 2003 Robert W. Powell. All rights reserved.
|
|