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;
}