简要描述:
说到底还是对图片的控件进行缩放。及缩放picturebox控件,该图片控件缩放的最大范围为其依赖的panel(或者其他)控件决定。
1.通过鼠标滚轮事件MouseWheel进行缩放,往前滚动为放大,往后滚动为缩小。每次滚动的数值随着滚动方向,正负号不同。所以直接相加即可。当然还应该考虑到缩放后所带来的图片出框等问题。
2.鼠标拖拽应该考虑到,图片拖出去的问题。
1.添加几个鼠标事件:
MouseWheel、MouseDown、MouseMove1
2.MouseWheel:滚轮事件,控件中如果没有,需要手动添加:
// skinPictureBox1添加滚轮缩放时间
skinPictureBox1.MouseWheel += new MouseEventHandler(skinPictureBox1_MouseWheel);
skinPictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
3.上述事件代码如下:
/// <summary>
/// skinPictureBox1滚动缩放
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void skinPictureBox1_MouseWheel(object sender, MouseEventArgs e)
{
try
{
var t = skinPictureBox1.Size;
int widthDate = t.Width + e.Delta;
int heightDate = t.Height + e.Delta;
// 限制缩小范围
if (widthDate < skinPanel11.Width || heightDate < skinPanel11.Height)
{
return;
}
// 限制放大范围5倍
if (widthDate > (skinPanel11.Width*5) || heightDate > (skinPanel11.Height*5))
{
return;
}
t.Width = widthDate;
t.Height = heightDate;
skinPictureBox1.Size = t;
// 防止缩放后,图片出框
if (Math.Abs(skinPictureBox1.Location.X) > (skinPictureBox1.Width - skinPanel11.Width)
|| Math.Abs(skinPictureBox1.Location.Y) > (skinPictureBox1.Height - skinPanel11.Height))
{
skinPictureBox1.Location = new Point(skinPanel11.Width - t.Width, skinPanel11.Height - t.Height);
}
// 缩放后,其他业务处理
}
catch (Exception x)
{
logger.Error("缩放异常:" + x.Message);
}
}
//鼠标移动
int xPos = 0;
int yPos = 0;
private void skinPictureBox1_MouseDown(object sender, MouseEventArgs e)
{
xPos = e.X;//当前x坐标.
yPos = e.Y;//当前y坐标.
}
/// <summary>
/// 鼠标移动事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void skinPictureBox1_MouseMove1(object sender, MouseEventArgs e)
{
try
{
// 鼠标按下拖拽图片
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right)
{
// 限制拖拽出框
if ((skinPictureBox1.Width - skinPanel11.Width) <= 0
|| (skinPictureBox1.Height - skinPanel11.Height) <= 0)
{
skinPictureBox1.Location = new Point(0,0);
}
else
{
if ((skinPictureBox1.Top + Convert.ToInt16(e.Y - yPos)) <= 0
&& (skinPictureBox1.Left + Convert.ToInt16(e.X - xPos)) <= 0
&& (skinPictureBox1.Right + Convert.ToInt16(e.X - xPos)) >= skinPanel11.Width
&& (skinPictureBox1.Bottom + Convert.ToInt16(e.Y - yPos)) >= skinPanel11.Height)
{
skinPictureBox1.Left += Convert.ToInt16(e.X - xPos);//设置x坐标.
skinPictureBox1.Top += Convert.ToInt16(e.Y - yPos);//设置y坐标.
}
}
}
// 拖放后,其他业务处理
}
catch (Exception dd)
{
logger.Error("鼠标移动异常:" + dd.Message);
}
}