Use the GDI library objects to draw rectangles that have rounded rectangles of a specified radius. The secret is to use a series of lines and arcs to form the rectangle as desired.
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); // Line
gp.AddArc(x + width - (radius * 2), y, radius * 2, radius * 2, 270, 90); // Corner
gp.AddLine(x + width, y + radius, x + width, y + height - (radius * 2)); // Line
gp.AddArc(x + width - (radius * 2), y + height - (radius * 2), radius * 2, radius * 2, 0, 90); // Corner
gp.AddLine(x + width - (radius * 2), y + height, x + radius, y + height); // Line
gp.AddArc(x, y + height - (radius * 2), radius * 2, radius * 2, 90, 90); // Corner
gp.AddLine(x, y + height - (radius * 2), x, y + radius); // Line
gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner
gp.CloseFigure();
g.DrawPath(p, gp);
gp.Dispose();
}
Explanation:
This method, DrawRoundRect
, is designed to draw a rectangle with rounded corners on a graphical interface using GDI+ in C#. It takes parameters for positioning, size, and styling:
Graphics g
: The graphics context on which the rectangle will be drawn.Pen p
: The pen used for drawing the outline of the rectangle.float x, float y
: The coordinates for the top-left corner of the rectangle.float width, float height
: The dimensions of the rectangle.float radius
: The radius of the rounded corners.
The method constructs a GraphicsPath
object (gp
) to define the shape of the rectangle:
- Straight Lines (
gp.AddLine
): These lines create the top, bottom, and sides of the rectangle, connecting the arcs that form the rounded corners. - Arcs for Corners (
gp.AddArc
): These arcs create the rounded corners. EachAddArc
call draws a quarter-circle. The parameters define the bounding rectangle for the arc, the start angle, and the sweep angle (in degrees). - Closing the Path (
gp.CloseFigure
): This ensures that the last point of the path connects back to the first point, creating a closed shape.
After defining the path, the method:
- Uses
g.DrawPath(p, gp)
to draw the path on theGraphics
objectg
using thePen
p
. - Disposes of the
GraphicsPath
object withgp.Dispose()
to free resources.
The method is useful for drawing custom shapes with smooth, rounded corners in GUI applications, providing a more visually appealing alternative to sharp-cornered rectangles.