1.Panel里放picturebox,picturebox大小与panel相同。
放大缩小:
在窗体load事件中加入
this.MouseWheel += splitContainer1_Panel1_MouseWheel;(我用的是splitContainer,panel同理)
void splitContainer1_Panel1_MouseWheel(object sender, MouseEventArgs e)
{
Rectangle rectangle=new Rectangle();
rectangle = splitContainer1.RectangleToClient(this.ClientRectangle);
if (rectangle.Contains(MousePosition)) //判断鼠标位置是否在图片区域内
{
double step = 1.2;//缩放倍率
if (e.Delta > 0)//放大
{
if (pictureBox3.Height < Screen.PrimaryScreen.Bounds.Height * 4)
{
pictureBox3.Size = new Size((int)(pictureBox3.Width * step), (int)(pictureBox3.Height * step));//调整picturebox大小
int px_add = (int)(pictureBox3.PointToClient(MousePosition).X * (step - 1.0));
int py_add = (int)(pictureBox3.PointToClient(MousePosition).Y * (step - 1.0));
pictureBox3.Location = new Point(pictureBox3.Location.X - px_add, pictureBox3.Location.Y - py_add);//调整picturebox位置
}
}
else//缩小
{
if (pictureBox3.Height > splitContainer1.Panel1.Height)
{
pictureBox3.Size = new Size((int)(pictureBox3.Width / step), (int)(pictureBox3.Height / step));
int px_add = (int)(pictureBox3.PointToClient(MousePosition).X * (1.0 - 1.0 / step));
int py_add = (int)(pictureBox3.PointToClient(MousePosition).Y * (1.0 - 1.0 / step));
pictureBox3.Location = new Point(pictureBox3.Location.X + px_add, pictureBox3.Location.Y + py_add);
}
}
}
拖动图片
Point mouseDownPoint = new Point();//鼠标按下时的坐标
Boolean isSelected = false;
private void pictureBox4_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseDownPoint.X = Cursor.Position.X; //注:全局变量mouseDownPoint前面已定义为Point类型
mouseDownPoint.Y = Cursor.Position.Y;
isSelected = true;
}
}
private void pictureBox4_MouseMove(object sender, MouseEventArgs e)
{
if (isSelected && IsMouseInPanel())//鼠标选中并且在panel内
{
this.pictureBox4.Left = this.pictureBox4.Left + (Cursor.Position.X - mouseDownPoint.X);
this.pictureBox4.Top = this.pictureBox4.Top + (Cursor.Position.Y - mouseDownPoint.Y);
mouseDownPoint.X = Cursor.Position.X;
mouseDownPoint.Y = Cursor.Position.Y;
}
}