C#,一种简单的方式实现滚动鼠标缩放图片,平移

1、缩放

 private void ImageShow_Load(object sender, EventArgs e)
        {
            pictureBox1.Load(@"E:\SQ1.jpg");
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox1.Dock = DockStyle.None;
        }

        private void pictureBox1_MouseEnter(object sender, EventArgs e)
        {
            pictureBox1.Focus();
            pictureBox1.Cursor = Cursors.SizeAll;
        }
        /// <summary>
        /// 放大,缩小图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
        {
            int i = e.Delta * SystemInformation.MouseWheelScrollLines / 5;

            pictureBox1.Width = pictureBox1.Width + i;//增加picturebox的宽度
            pictureBox1.Height = pictureBox1.Height + i;
            pictureBox1.Left = pictureBox1.Left - i / 2;//使picturebox的中心位于窗体的中心
            pictureBox1.Top = pictureBox1.Top - i / 2;//进而缩放时图片也位于窗体的中心
        }      

2、平移

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;  //注:全局变量mouseDownPoint前面已定义为Point类型  
                mouseDownPoint.Y = Cursor.Position.Y;
                isSelected = true;
            }  
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (isSelected && IsMouseInPanel())//确定已经激发MouseDown事件,和鼠标在picturebox的范围内
            {
                this.pictureBox1.Left = this.pictureBox1.Left + (Cursor.Position.X - mouseDownPoint.X);
                this.pictureBox1.Top = this.pictureBox1.Top + (Cursor.Position.Y - mouseDownPoint.Y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }  
        }
        private bool IsMouseInPanel()
        {
            if (this.pan_picture.Left < PointToClient(Cursor.Position).X && PointToClient(Cursor.Position).X < this.pan_picture.Left + this.pan_picture.Width && this.pan_picture.Top < PointToClient(Cursor.Position).Y && PointToClient(Cursor.Position).Y < this.pan_picture.Top + this.pan_picture.Height)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

      
        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            isSelected = false;
        }

 

posted on 2013-12-30 10:21  jin_qi_er  阅读(3135)  评论(1编辑  收藏  举报