最新动态
你的位置:金海岸娱乐 > 最新动态 >
Winform圆角按钮(无锯齿)
发布日期:2024-07-22 05:49    点击次数:138

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

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

图片

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

 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);        }

消除锯齿,对圆角区域进行填充

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);        }

在Paint事件中进行调用

e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;            if (RoundRadius > 0)            {                DrawRoundRegion();                FillRoundRegion(e.Graphics);            }

下面可以看下加第二段代码与不加的区别

图片

图片

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

图片

按钮自定义控件已封装:

☛☛☛点击获取☚☚☚

图片

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报。