1. 程式人生 > >C#影象顯示實現拖拽、錨點縮放功能

C#影象顯示實現拖拽、錨點縮放功能

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;   //記錄滑鼠左鍵按下時位置
                mouseDownPoint.Y = Cursor.Position.Y;                
                isMove = true;
                pictureBox1.Focus();    //滑鼠滾輪事件(縮放時)需要picturebox有焦點
            }
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;                
            }
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            pictureBox1.Focus();    //滑鼠在picturebox上時才有焦點,此時可以縮放
            if (isMove)
            {
                int x, y;           //新的pictureBox1.Location(x,y)
                int moveX, moveY;   //X方向,Y方向移動大小。
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = pictureBox1.Location.X + moveX;
                y = pictureBox1.Location.Y + moveY;                
                pictureBox1.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;                
            }
        }
        
        private void panel2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;   //記錄滑鼠左鍵按下時位置
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
            }
        }

        private void panel2_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }

        private void panel2_MouseMove(object sender, MouseEventArgs e)
        {
            panel2.Focus();  //滑鼠不在picturebox上時焦點給別的控制元件,此時無法縮放            
            if (isMove)
            {
                int x, y;           //新的pictureBox1.Location(x,y)
                int moveX, moveY;   //X方向,Y方向移動大小。
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = pictureBox1.Location.X + moveX;
                y = pictureBox1.Location.Y + moveY;
                pictureBox1.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }