C#绘制圆角矩形

来源:互联网 发布:互联网职位 知乎 编辑:程序博客网 时间:2024/06/10 17:32

C#使用图形组合的方法绘制圆角矩形

在C#中的System.Drawing.Graphics类里为我们提供了诸多绘图方法,但圆角矩形这个形状却没有提供方法去绘制,但是我们可以通过图形组合的方法来绘制圆角矩形,如图。

图形组合

代码:

using System.Drawing;using System.Drawing.Drawing2D;/// <summary>/// 填充一个圆角矩形/// </summary>/// <param name="b">源图片</param>/// <param name="brush">笔刷</param>/// <param name="x">X坐标</param>/// <param name="y">Y坐标</param>/// <param name="width">宽度</param>/// <param name="height">高度</param>/// <param name="radius">半径</param>private void FillRoundRect(Bitmap b, Brush brush, int x, int y, int width, int height, int radius){    //防止半径过大    if (radius * 2 > width)        radius = width / 2;    if (radius * 2 > height)        radius = height / 2;    Graphics g = Graphics.FromImage(b);    //防止锯齿    g.SmoothingMode = SmoothingMode.HighQuality;    //绘制四个圆角    g.FillEllipse(brush, x, y, radius * 2, radius * 2);    g.FillEllipse(brush, x + (width - radius * 2), y, radius * 2, radius * 2);    g.FillEllipse(brush, x, y + (height - radius * 2), radius * 2, radius * 2);    g.FillEllipse(brush, x + (width - radius * 2), y + (height - radius * 2), radius * 2, radius * 2);    //绘制横竖两个矩形    g.FillRectangle(brush, x + radius, y, width - radius * 2, height);    g.FillRectangle(brush, x, y + radius, width, height - radius * 2);}

调用也很简单:

Bitmap b = new Bitmap(150, 150);FillRoundRect(b, new SolidBrush(), 0, 0, 150, 150, 30);pic_Image.Image = b;

效果图:
Fill Round Rect


这样一来,填充圆角矩形是实现了,但绘制边框就要用到另一种方法了:绘制四个角的圆弧,再绘制四条边。

代码:

using System.Drawing;using System.Drawing.Drawing2D;/// <summary>/// 绘制一个圆角矩形/// </summary>/// <param name="b">源图片</param>/// <param name="pen"></param>/// <param name="x">X坐标</param>/// <param name="y">Y坐标</param>/// <param name="width">宽度</param>/// <param name="height">高度</param>/// <param name="radius">半径</param>private void DrawRoundRect(Bitmap b, Pen pen, int x, int y, int width, int height, int radius){    //防止半径过大    if (radius * 2 > width)        radius = width / 2;    if (radius * 2 > height)        radius = height / 2;    Graphics g = Graphics.FromImage(b);    //防止锯齿    g.SmoothingMode = SmoothingMode.HighQuality;    //绘制四个圆弧    g.DrawArc(pen, x, y, radius * 2, radius * 2, 270, -90);    g.DrawArc(pen, x + (width - radius * 2), y, radius * 2, radius * 2, -90, 90);    g.DrawArc(pen, x, y + (height - radius * 2), radius * 2, radius * 2, 90, 90);    g.DrawArc(pen, x + (width - radius * 2), y + (height - radius * 2), radius * 2, radius * 2, 0, 90);    //四条直线边    g.DrawLine(pen, x, y + radius, x, y + height - radius);    g.DrawLine(pen, x + width, y + radius, x + width, y + height - radius);    g.DrawLine(pen, x + radius, y, x + width - radius, y);    g.DrawLine(pen, x + radius, y + height, x + width - radius, y + height);}

调用同上,效果图:
Draw Round Rect

当然,你也可以用最普遍的GraphicsPath的方法来绘制圆角矩形。

原创粉丝点击