SoFunction
Updated on 2025-03-07

C# How to draw rounded rectangles

This article describes the method of drawing rounded rectangles in C#. Share it for your reference. The specific implementation method is as follows:

protected void Page_Load(object sender, EventArgs e)
{
 Bitmap bm = new Bitmap(800, 600);
 Graphics g = (bm);
 (,new Rectangle(0,0,800,600));
 FillRoundRectangle(g,,new Rectangle(100, 100, 100, 100), 8);
 DrawRoundRectangle(g, ,new Rectangle(100, 100, 100, 100), 8);
 (, );
 ();
 ();
}
public static void DrawRoundRectangle(Graphics g,Pen pen,Rectangle rect, int cornerRadius)
{
 using (GraphicsPath path = CreateRoundedRectanglePath(rect, cornerRadius))
 {
  (pen, path);
 }
}
public static void FillRoundRectangle(Graphics g, Brush brush,Rectangle rect, int cornerRadius)
{
 using (GraphicsPath path = CreateRoundedRectanglePath(rect, cornerRadius))
 {
  (brush, path);
 }
}
internal static GraphicsPath CreateRoundedRectanglePath(Rectangle rect, int cornerRadius)
{
 GraphicsPath roundedRect = new GraphicsPath();
 (, , cornerRadius * 2, cornerRadius * 2, 180, 90);
 ( + cornerRadius, ,  - cornerRadius * 2, );
 ( +  - cornerRadius * 2, , cornerRadius * 2, cornerRadius * 2, 270, 90);
 (,  + cornerRadius * 2, ,  +  - cornerRadius * 2);
 ( +  - cornerRadius * 2,  +  - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90);
 ( - cornerRadius * 2, ,  + cornerRadius * 2, );
 (,  - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90);
 (,  - cornerRadius * 2, ,  + cornerRadius * 2);
 ();
 return roundedRect;
}

I hope this article will be helpful to everyone's C# programming.