C#控件picturebox实现图像拖拽和缩放

2020-01-05 09:39:29刘景俊

2.图像缩放

核心思想:利用picturebox的zoom模式,根据图像显示大小更改picturebox大小,记录鼠标位置补偿缩放位移,实现锚点缩放,即以鼠标位置为中心进行缩放。
zoomstep --- 自己定义滚轮滑动缩放大小

代码:


//实现锚点缩放(以鼠标所指位置为中心缩放);
  //步骤:
  //①先改picturebox长宽,长宽改变量一样;
  //②获取缩放后picturebox中实际显示图像的长宽,这里长宽是不一样的;
  //③将picturebox的长宽设置为显示图像的长宽;
  //④补偿picturebox因缩放产生的位移,实现锚点缩放。
  // 注释:为啥要②③步?由于zoom模式的机制,把picturebox背景设为黑就知道为啥了。
  //这里需要获取zoom模式下picturebox所显示图像的大小信息,添加 using System.Reflection;
  //pictureBox1_MouseWheel事件没找到。。。手动添加,别忘在Form1.Designer.cs的“Windows 窗体设计器生成的代码”里加入:  
  //this.pictureBox1.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseWheel)。
  private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
  {
   int x = e.Location.X;
   int y = e.Location.Y;
   int ow = pictureBox1.Width;
   int oh = pictureBox1.Height;   
   int VX, VY;  //因缩放产生的位移矢量
   if (e.Delta > 0) //放大
   {
    //第①步
    pictureBox1.Width += zoomStep;
    pictureBox1.Height += zoomStep;
    //第②步
    PropertyInfo pInfo = pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
     BindingFlags.NonPublic);
    Rectangle rect = (Rectangle)pInfo.GetValue(pictureBox1, null);
    //第③步
    pictureBox1.Width = rect.Width;
    pictureBox1.Height = rect.Height;
   }
   if (e.Delta < 0) //缩小
   {
    //防止一直缩成负值
    if (pictureBox1.Width < myBmp.Width / 10)
     return;
    
    pictureBox1.Width -= zoomStep;
    pictureBox1.Height -= zoomStep;
    PropertyInfo pInfo = pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
     BindingFlags.NonPublic);
    Rectangle rect = (Rectangle)pInfo.GetValue(pictureBox1, null);
    pictureBox1.Width = rect.Width;
    pictureBox1.Height = rect.Height;
   }
   //第④步,求因缩放产生的位移,进行补偿,实现锚点缩放的效果
   VX = (int)((double)x * (ow - pictureBox1.Width) / ow);
   VY = (int)((double)y * (oh - pictureBox1.Height) / oh);
   pictureBox1.Location = new Point(pictureBox1.Location.X + VX, pictureBox1.Location.Y + VY);
}