C#实现图像拖拽以及锚点缩放功能
本文主要实现C#窗体图像拖拽以及锚点缩放功能
1、新建Windows窗体应用项目,添加一个panel控件,在panel控件上添加picturebox控件
代码如下:
using System; using System.Drawing; using System.Windows.Forms; namespace SupremeWindowsForms { public partial class Form3 : Form { #region Fields and Properties Size size; bool flag = false; Point pointLast; Point pointCurrent; #endregion #region Methods public Form3() { InitializeComponent(); this.MouseWheel += Form3_MouseWheel; this.pictureBox1.Image = Image.FromFile(@"F:\Person\Longteng\LongtengSln\SupremeWindowsForms\picture\1.jpg"); this.pictureBox1.MouseDown += PictureBox1_MouseDown; this.pictureBox1.MouseMove += PictureBox1_MouseMove; this.pictureBox1.MouseUp += PictureBox1_MouseUp; size = panel1.Size; } /// <summary> /// 鼠标的滚动轮向上下的滚动 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form3_MouseWheel(object sender, MouseEventArgs e) { if (e.Delta > 0)//鼠标的滚动轮向上的滚动 { size.Width += (int)(((float)e.Delta / (float)size.Width) * size.Width); size.Height += (int)(((float)e.Delta / (float)size.Height) * size.Height); if (size.Width > panel1.Parent.Size.Width || size.Height > panel1.Parent.Size.Height) { size = pictureBox1.Size; } panel1.Size = size; } else //鼠标的滚动轮向下的滚动 { size.Width -= (int)(((float)-e.Delta / (float)size.Width) * size.Width); size.Height -= (int)(((float)-e.Delta / (float)size.Height) * size.Height); if (size.Width <= 0 || size.Height <= 0) { size = new Size(60, 60); } panel1.Size = size; } } /// <summary> /// 在图片控件上按住鼠标左键 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PictureBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point point = new Point(e.X, e.Y);//注意:鼠标的坐标位置,是以当前的窗体的坐标为基准 Console.WriteLine($"鼠标按下的位置坐标:{point.X},{point.Y}"); Point point1 = PointToScreen(point); Console.WriteLine($"鼠标按下的位置坐标PointToScreen:{point1.X},{point1.Y}"); pointLast = point1; flag = true; } } /// <summary> /// 在图片控件上按住鼠标左键,移动 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PictureBox1_MouseMove(object sender, MouseEventArgs e) { if (flag) { pointCurrent = MousePosition;//注意:以屏幕坐标为基准 Console.WriteLine($"鼠标拖动的位置坐标:{pointCurrent.X},{pointCurrent.Y}"); Point point = new Point(pointCurrent.X - pointLast.X, pointCurrent.Y - pointLast.Y); Console.WriteLine($"鼠标Offset 坐标:{point.X},{point.Y}"); this.panel1.Location = point; } } /// <summary> /// 在图片控件上按住鼠标左键,移动之后,松开 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PictureBox1_MouseUp(object sender, MouseEventArgs e) { if (flag) { flag = false; } } #endregion } }
运行效果:
鼠标滚动滚轮缩放效果-放大
鼠标滚动滚轮缩放效果-缩小
拖动效果
注意:
1、控件上鼠标点击之后其他操作获取的鼠标的位置是相对当前窗体的位置,而鼠标移动的时候,获取的位置是相对于屏幕的位置。位置的转换可以通过PointToScreen和PointToClient进行转换
龙腾一族至尊龙骑