自定义圆角矩形控件

构造函数里设置相应的style,并将背景色设为透明

this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.BackColor = Color.Transparent;

在OnSizeChanged中添加标记,改变全局变量_path

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);

            _isSizeChanged = true;
        }

在OnPaint绘制边线

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (_isSizeChanged)
            {
                updateRegion();
                _isSizeChanged = false;
            }

            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            g.FillPath(Brushes.White, _path);
            g.DrawPath(_penBorderline, _path);
        }

辅助函数,用来更新path

        private void updateRegion()
        {
            int x = 0;
            int y = 0;
            int width = this.Width - 1;  //这里需要-1,不然会超出边界
            int height = this.Height - 1;   //这里需要-1,不然会超出边界
            int roundRadius = _roundRadius;
            _path = new GraphicsPath();//这里用来清空前面保存的_path

            if (roundRadius > 0)
            {
                _path.AddArc(x, y, roundRadius, roundRadius, 180, 90);                                 // 左上角
                _path.AddArc(width - roundRadius, y, roundRadius, roundRadius, 270, 90);                 // 右上角
                _path.AddArc(width - roundRadius, height - roundRadius, roundRadius, roundRadius, 0, 90);  // 右下角
                _path.AddArc(x, height - roundRadius, roundRadius, roundRadius, 90, 90);                 // 左下角
            }
            else
            {
                _path.AddLine(x + roundRadius, y, width - roundRadius, y);                         // 顶端
                _path.AddLine(width, y + roundRadius, width, height - roundRadius);        // 右边
                _path.AddLine(width - roundRadius, height, x + roundRadius, height);       // 底边
                _path.AddLine(x, y + roundRadius, x, height - roundRadius);                        // 左边;
            }

            _path.CloseAllFigures();
        }

全局变量

        bool _isSizeChanged = false;

        GraphicsPath _path;
        int _roundRadius = 50;
        Pen _penBorderline = new Pen(Color.Black);
原文地址:https://www.cnblogs.com/YYi_H/p/2159251.html