/* sharecodes.org 友情提醒:尊重知识,转载请注明原创作者、出处! */ /// <summary> /// C# GDI+ 绘制圆角矩形 /// </summary> /// <param name="g">Graphics 对象</param> /// <param name="rectangle">Rectangle 对象,圆角矩形区域</param> /// <param name="borderColor">边框颜色</param> /// <param name="borderWidth">边框宽度</param> /// <param name="r">圆角半径</param> public static void DrawRoundRectangle(Graphics g, Rectangle rectangle, Color borderColor, float borderWidth, int r) { // 如要使边缘平滑,请取消下行的注释 // g.SmoothingMode = SmoothingMode.HighQuality; // 由于边框也需要一定宽度,需要对矩形进行修正 rectangle = new Rectangle(rectangle.X, rectangle.Y, rectangle.Width - 1, rectangle.Height - 1); Pen p = new Pen(borderColor, borderWidth); // 调用 getRoundRectangle 得到圆角矩形的路径,然后再进行绘制 g.DrawPath(p, getRoundRectangle(rectangle, r)); } /// <summary> /// 根据普通矩形得到圆角矩形的路径 /// </summary> /// <param name="rectangle">原始矩形</param> /// <param name="r">半径</param> /// <returns>图形路径</returns> private static GraphicsPath getRoundRectangle(Rectangle rectangle, int r) { int l = 2 * r; // 把圆角矩形分成八段直线、弧的组合,依次加到路径中 GraphicsPath gp = new GraphicsPath(); gp.AddLine(new Point(rectangle.X + r, rectangle.Y), new Point(rectangle.Right - r, rectangle.Y)); gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Y, l, l), 270F, 90F); gp.AddLine(new Point(rectangle.Right, rectangle.Y + r), new Point(rectangle.Right, rectangle.Bottom - r)); gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Bottom - l, l, l), 0F, 90F); gp.AddLine(new Point(rectangle.Right - r, rectangle.Bottom), new Point(rectangle.X + r, rectangle.Bottom)); gp.AddArc(new Rectangle(rectangle.X, rectangle.Bottom - l, l, l), 90F, 90F); gp.AddLine(new Point(rectangle.X, rectangle.Bottom - r), new Point(rectangle.X, rectangle.Y + r)); gp.AddArc(new Rectangle(rectangle.X, rectangle.Y, l, l), 180F, 90F); return gp; }
/* sharecodes.org 友情提醒:尊重知识,转载请注明原创作者、出处! */ // 在 Form 上放置一 Panel,命名为 panel1,调用绘图方法 DrawRoundRectangle(panel1.CreateGraphics(), new Rectangle(10, 10, 100, 80), ColorTranslator.FromHtml("#CCFF66"), 4F, 20); DrawRoundRectangle(panel1.CreateGraphics(), new Rectangle(120, 10, 100, 80), ColorTranslator.FromHtml("#FF66FF"), 4F, 20); DrawRoundRectangle(panel1.CreateGraphics(), new Rectangle(240, 10, 100, 80), ColorTranslator.FromHtml("#6699FF"), 4F, 20);