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);
pictureBox1.Top += Convert.ToInt16(e.Y - yPos);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
this.pictureBox1.Focus();
MoveFlag = true;
xPos = e.X;
yPos = e.Y;
}