C#控件控件picturebox实现图像拖拽和缩放实现图像拖拽和缩放
主要为大家详细介绍了C#控件picturebox实现图像拖拽和缩放,具有一定的参考价值,感兴趣的小伙伴们可以参
考一下
本文实例为大家分享了C# picturebox实现图像拖拽和缩放的具体代码,供大家参考,具体内容如下
1.核心步骤:核心步骤:
①新建Point类型全局变量mouseDownPoint,记录拖拽过程中鼠标位置;
②MouseDown事件记录Cursor位置;
③MouseMove事件计算移动矢量,并更新pictureBox1.Location。
代码:
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方向移动大小。