c#画圆形控件

如下:
1、如何解决调用DrawString时报“参数无效”的问题?
2、如何在改变控件尺寸时,圆的直径也跟着改变?
3、如何只在圆内响应单机事件,但是不在圆外控件内的那部分响应单机事件?
4、如何在最小化窗体后,控件的圆以及圆内的文字实现重新的绘制?
本博客将会解决上述四个问题,如下:

在这里插入图片描述

class MyControl : Control
    {


        public MyControl()
        {
            //this.BackColor = Color.Yellow;
            //this.Size = new Size(100,100);
            //this.SetStyle(ControlStyles.UserPaint ,true );
            // this.SetStyle(ControlStyles.AllPaintingInWmPaint, true );
            // this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

            this.SetStyle(ControlStyles.ResizeRedraw, true);//空间大小改变时,控件会重绘

        }




        protected override void OnPaint(PaintEventArgs e)
        {

            base.OnPaint(e);

            int width = this.Width;
            int height = this.Height;
            int radius = width < height ? width : height;//以最短的边最为圆的直径
            Graphics graphics = this.CreateGraphics();
            //graphics.Clear( Color .FromArgb (255,240,240,240) );
            Rectangle rectangle = new Rectangle(0, 0, radius, radius);


            graphics.SmoothingMode = SmoothingMode.AntiAlias;//消除锯齿
            Brush brush = new SolidBrush(Color.Red);//指定画刷的颜色
            graphics.FillEllipse(brush, new Rectangle(0, 0, radius, radius));//填充一个圆


            Pen pen = new Pen(Color.Black, 2);//指定画笔的颜色和线宽
            graphics.DrawEllipse(pen, rectangle);//绘制圆的边界

            string text = this.Text;
            brush = new SolidBrush(Color.Black);//指定画刷画文本的颜色

            Font font = this.Font;

            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;//字符水平对齐方式
            sf.LineAlignment = StringAlignment.Center;//字符垂直对齐方式
            graphics.DrawString(text, font, brush, new RectangleF(0, 0, radius, radius), sf);


            #region  使控件的单击事件只在圆内触发,而不是在矩形控件范围内触发,消除在圆外和控件内的区域响应单机事件的bug
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            path.AddEllipse(0, 0, radius, radius);
            this.Region = new Region(path);
            #endregion


            //font.Dispose();//当控件的size改变时,如果调用了 font.Dispose(),那么font.Height会报异常,因为没有重新实例化font类,导致DrawString会报参数无效,所以也可以不调用font.dispose,这样就可以不用捕获异常了
            brush.Dispose();
            pen.Dispose();
            graphics.Dispose();

        }
    }

觉得有用点个赞呦!毕竟研究了几个小时,哈哈~


版权声明:本文为qq_34059233原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。