Winform圆角按钮(无锯齿)

前言:不知道从什么时候开始,大家喜欢上了这种平滑式的设计,对于原来简简单单、方方正正的设计开始置之不理了(我到现在还独爱Windows 8的设计);在Winform上做出来这种平滑的效果相对来说还是比较麻烦的,不像CSS一行代码就可搞定。

关于圆角的代码想必很多人都用GDI+实现过,但是直接的效果可能不太理想,大部分情况下都有锯齿;其实对于纯色背景的情况下,这种锯齿还是可以消除掉的。.

  1. 下面是一段绘制圆角的代码,但是这样直接绘制出来的话,就会产生锯齿

     private void DrawRoundRegion()        {            Rectangle rect = new Rectangle(-1, -1, base.Width + 1, base.Height);            Rectangle rect2 = new Rectangle(rect.Location, new Size(_roundRadius, _roundRadius));            GraphicsPath graphicsPath = new GraphicsPath();            graphicsPath.AddArc(rect2, 180f, 90f);//左上角            rect2.X = rect.Right - _roundRadius;            graphicsPath.AddArc(rect2, 270f, 90f);//右上角            rect2.Y = rect.Bottom - _roundRadius;            rect2.Width += 1;            rect2.Height += 1;            graphicsPath.AddArc(rect2, 360f, 90f);//右下角               rect2.X = rect.Left;            graphicsPath.AddArc(rect2, 90f, 90f);//左下角            graphicsPath.CloseFigure();            base.Region = new Region(graphicsPath);        }
  1. 消除锯齿,对圆角区域进行填充

    private void FillRoundRegion(Graphics graphics)        {            Rectangle rect = ClientRectangle;            Rectangle rect2 = new Rectangle(rect.Location, new Size(_roundRadius, _roundRadius));            GraphicsPath graphicsPath = new GraphicsPath();            graphicsPath.AddArc(rect2, 180f, 90f);//左上角            rect2.X = rect.Right - _roundRadius - 1;            graphicsPath.AddArc(rect2, 270f, 90f);//右上角            rect2.Y = rect.Bottom - _roundRadius - 1;            graphicsPath.AddArc(rect2, 0f, 90f);//右下角               rect2.X = rect.Left;            graphicsPath.AddArc(rect2, 90f, 90f);//左下角            graphicsPath.CloseFigure();            graphics.FillPath(new SolidBrush(HoverBackColor == Color.Empty ? _BackColor : HoverBackColor), graphicsPath);        }
  1. Paint事件中进行调用

    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
                if (RoundRadius > 0)            {                DrawRoundRegion();                FillRoundRegion(e.Graphics);            }
  1. 下面可以看下加第二段代码与不加的区别

Winform圆角按钮(无锯齿)

Winform圆角按钮(无锯齿)

  1. 可以发现效果还是很明显的,最后我们为了方便使用加入一个Type类型,来实现简单的换色效果

    Winform圆角按钮(无锯齿)

按钮自定义控件已封装:

微信小程序 搜索:资源小记