C# 对图片进行缩放拖动

图片在窗体中显示,实现了拖动图片,放大缩小图片的功能。

解决了图片闪烁的问题。

创建一个空白窗体,复制以下代码即可

    public partial class Form1 : Form
    {
        int width, height;
        decimal percent = 0m;
        string path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg"; //示例图片
        Image img = null;
        Rectangle rect;

        public Form1()
        {
            InitializeComponent();
            this.DoubleBuffered = true; //双缓冲,防止闪烁
            img = Image.FromFile(path);
            width = img.Width;
            height = img.Height;
            percent = Convert.ToDecimal(width) / Convert.ToDecimal(height);
            rect = new Rectangle(0, 0, width, height);
            this.MouseWheel += new MouseEventHandler(Form1_MouseWheel);
            this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
            this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove);
            this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseUp);
        }

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

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            rect.Width = width;
            rect.Height = height;
            e.Graphics.Clear(this.BackColor);
            e.Graphics.DrawImage(img, rect);
        }

        bool leftButton = false;

        Point mouseDownPoint;

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            mouseDownPoint = e.Location;
            mouseDownPoint.Offset(-rect.X, -rect.Y);
            leftButton = e.Button == MouseButtons.Left;
            if (leftButton && rect.Contains(e.Location))
                Cursor.Current = Cursors.Hand;
            else
                Cursor.Current = Cursors.Default;
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (leftButton)
            {
                if (rect.Contains(e.Location))
                {
                    Cursor.Current = Cursors.Hand;
                    Point nowPoint = e.Location;
                    nowPoint.Offset(-mouseDownPoint.X, -mouseDownPoint.Y);
                    rect.Location = nowPoint;
                    this.Invalidate();
                }
                else
                    Cursor.Current = Cursors.Default;
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            if (leftButton)
            {
                Cursor.Current = Cursors.Default;
                leftButton = false;
            }
        }
    }