C# 使用Graphics绘制图片时发生闪烁的问题

在做某功能时,需要实现用鼠标滚轮放大缩小图片,直接在MouseWheel中绘制图片时发生闪烁

百度后顺利解决

几个步骤

1.设置Form的DoubleBuffered属性为True

2.在MouseWheel中调用 this.Invalidate()方法(会触发OnPaint事件)

3.重写OnPaint,在OnPaint中绘制需要绘制的图像

代码如下:

    public partial class Form1 : Form
    {
        int width, height;
        string path = "C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg";
        Image img = null;

        public Form1()
        {
            InitializeComponent();
            this.DoubleBuffered = true;
            img = Image.FromFile(path);
            width = img.Width;
            height = img.Height;
            this.MouseWheel += new MouseEventHandler(Form1_MouseWheel);
        }

        void Form1_MouseWheel(object sender, MouseEventArgs e)
        {
            width += (e.Delta / 5);
            height += (e.Delta / 5);
            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Rectangle rect = new Rectangle(0, 0, width, height);
            e.Graphics.Clear(SystemColors.Control);
            e.Graphics.DrawImage(img, rect);
        }
    }
原文地址:https://www.cnblogs.com/xyz0835/p/4119129.html