C# 簡易實現圖片的縮放以及圖片的平移

C# 簡易實現圖片的縮放以及圖片的平移

  • 用到了幾個事件:MouseUp 、MouseDown以及MouseWheel
  • 使用原生PictureBox

MouseWheel:滾輪監聽事件

 pictureBox1.MouseWheel += new MouseEventHandler(pbxDrawing_MouseWheel);
 private void pbxDrawing_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
        {
        //判斷上滑還是下滑
            if (e.Delta < 0)
            {
            //計算縮放大小
                this.pictureBox1.Width = this.pictureBox1.Width * 9 / 10;
                this.pictureBox1.Height = this.pictureBox1.Height * 9 / 10;
            }
            else
            {
                this.pictureBox1.Width = this.pictureBox1.Width * 11 / 10;
                this.pictureBox1.Height = this.pictureBox1.Height * 11 / 10;
            }
        }

下面定義三個變量用來儲存鼠標按下時的座標(X、Y),以及一個變量代表鼠標按下或擡起的操作,直接上代碼:


        int xPos;
        int yPos;
        bool MoveFlag;
    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            //鼠標已經擡起
            MoveFlag = false;
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            //只在鼠標按下時繪製移動
            if (MoveFlag)
            {
                pictureBox1.Left += Convert.ToInt16(e.X - xPos);//設置x座標.
                pictureBox1.Top += Convert.ToInt16(e.Y - yPos);//設置y座標.
            }
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            this.pictureBox1.Focus();
            MoveFlag = true;//已經按下.
            xPos = e.X;//當前x座標.
            yPos = e.Y;//當前y座標.
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章