C#解决在Winform中绘图异常闪烁问题

1,问题描述:

  • 在winform中使用Graphics进行绘图,绘图效果却呈现异常闪烁。

2,解决办法:

  • 使用 SetStyle() 设置相应特性:
cs 复制代码
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);   //   禁止擦除背景.
this.SetStyle(ControlStyles.DoubleBuffer, true);   //   双缓冲
  • 建立临时对象,在临时对象上绘制完成后再一次性赋值给控件。
cs 复制代码
 Bitmap map = new Bitmap(panel1.Width, panel1.Height);
            using (Graphics g = Graphics.FromImage(map))
            {
                g.Clear(SystemColors.Control);
                g.FillPie(Brushes.SlateBlue, rec, 0, 360 - availDegree);
                //计算字符串插入位置坐标
                double degree = ((360 - availDegree) / 180 * Math.PI) / 2;
                Point center = new Point(rec.X + panel1.Width / 2, rec.Y + panel1.Height / 2);
                PointF p1 = new PointF((float)(center.X + Math.Cos(degree) * (min / 2)), (float)(center.Y + Math.Sin(degree) * (min / 2)));
                g.DrawString($"已使用:{Math.Round((1 - pc.AvailablePhysicalMemory * 1.0 / pc.TotalPhysicalMemory) * 100, 2, MidpointRounding.AwayFromZero)}%", new Font("微软雅黑", 8, FontStyle.Bold), Brushes.Red, new Point(10, 10));
                g.FillPie(Brushes.Green, rec, 360 - availDegree, availDegree);

            }
            panel1.BackgroundImage = map;

3,注意点:

cs 复制代码
 protected void SetStyle(ControlStyles flag, bool value);

该方法属于protected类型位于Control类中,即只能在Control类中被调用或者在继承自Control的子类中被调用

所以在继承自Control的类Form1中可以被直接调用:

cs 复制代码
this.SetStyle(ControlStyles.UserPaint, true);

this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);   //   禁止擦除背景.

 this.SetStyle(ControlStyles.DoubleBuffer, true);   //   双缓冲

但是如果想将其应用于Form1类中定义的panel01对象则必须通过反射进行设置。

cs 复制代码
//因为该方法是保护类型protect 只能在自己类或者其继承类中调用,所以这里用反射
            System.Reflection.MethodInfo method = typeof(Panel).GetMethod("SetStyle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            method.Invoke(panel1, new object[] { ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer | ControlStyles.UserPaint, true });

亦或是在派生自Panel的类型中进行设置。

cs 复制代码
 class CustomPanel:Panel
    {
        public CustomPanel()
        {
            this.SetStyle(ControlStyles.UserPaint | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
        }
    }
相关推荐
不知所云,1 小时前
qt cmake自定义资源目录,手动加载资源(图片, qss文件)
开发语言·qt
安冬的码畜日常2 小时前
【玩转 JS 函数式编程_006】2.2 小试牛刀:用函数式编程(FP)实现事件只触发一次
开发语言·前端·javascript·函数式编程·tdd·fp·jasmine
阑梦清川2 小时前
Java继承、final/protected说明、super/this辨析
java·开发语言
PythonFun2 小时前
Python批量下载PPT模块并实现自动解压
开发语言·python·powerpoint
Death2002 小时前
Qt 6 相比 Qt 5 的主要提升与更新
开发语言·c++·qt·交互·数据可视化
机器视觉知识推荐、就业指导2 小时前
使用Qt实现实时数据动态绘制的折线图示例
开发语言·qt
快乐就好ya3 小时前
Java多线程
java·开发语言
CS_GaoMing4 小时前
Centos7 JDK 多版本管理与 Maven 构建问题和注意!
java·开发语言·maven·centos7·java多版本
2401_858120534 小时前
Spring Boot框架下的大学生就业招聘平台
java·开发语言
转调5 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode