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坐标.
        }

你可能感兴趣的:(c#)