July 14, 2005

Drawing Rounded Rectangles

Based on some code from here I tidied it up a bit.
using System.Drawing;
using System.Drawing.Drawing2D;

class GraphicsHelper
{
 #region Drawing Rounded Rectangles

 /// <summary>
 /// Draw a rounded rectangle with the specified radius of the
 ///  rounded corners
 /// </summary>
 /// <param name="pen"></param>
 /// <param name="left"></param>
 /// <param name="top"></param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <param name="radius">radius of the rounded corners</param>
 public static void _DrawRoundedRectangle(Graphics graphics, Pen pen,
  int left, int top, int width, int height, int radius)
 {
  using (GraphicsPath gp = new GraphicsPath())
  {
   _AddRoundedRectPath(gp, left, top, width, height, radius);
   gp.CloseFigure();
   graphics.DrawPath(pen, gp);
  }
 }

 /// <summary>
 /// Draw a filled rounded rectangle with the specified radius
 /// of the rounded corners
 /// </summary>
 /// <param name="brush"></param>
 /// <param name="left"></param>
 /// <param name="top"></param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <param name="radius">radius of the rounded corners</param>
 public static void FillRoundedRectangle(Graphics graphics,
  Brush brush, int left, int top, int width, int height,
  int radius)

 {
  using (GraphicsPath gp = new GraphicsPath())
  {
   _AddRoundedRectPath(gp, left, top, width, height, radius);
   gp.CloseFigure();
   graphics.FillPath(brush, gp);
  }
 }

 /// <summary>
 /// Add a rounded rectangle to the given graphics path with
 /// the specified radius of the rounded corners
 /// </summary>
 /// <param name="gp"></param>
 /// <param name="left"></param>
 /// <param name="top"></param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <param name="radius">radius of the rounded corners</param>
 private static void _AddRoundedRectPath(GraphicsPath gp,
  int left, int top, int width, int height, int radius)
 {
  // Top line
  gp.AddLine(left+radius, top,  left+width-radius, top);
  // Top right arc
  gp.AddArc(left+width-radius, top, radius, radius, 270, 90);

  // Right hand side line
  gp.AddLine(left+width, top+radius, left+ width, top+height-radius);
  // Bottom right arc
  gp.AddArc(left+width-radius, top+height-radius,
   radius, radius, 0, 90);

  //  Bottom line
  gp.AddLine(left+width-radius, top+height, left+radius, top+height);
  //  Bottom left arc
  gp.AddArc(left, top+height-radius, radius, radius, 90, 90);

  // Left hand side line
  gp.AddLine(left, top+height-radius, left, top+radius);
  // Top left arc
  gp.AddArc(left, top, radius, radius, 180, 90);
 }

 #endregion Drawing Rounded Rectangles
}

No comments: