最近一个项目需要涉及到图片的全屏显示以及缩放拖动功能,其中缩放实现需要考虑的一点就是为了有更好的用户体验,需要在缩放的时候以光标所处位置为参考点,进行缩放操作,简单来说就是,缩放前后光标在图片上所处的位置保持不变。
- 实现原理:把图片放在picturebox中,通过一系列调整,使图片完全占满box,每次通过改变box的size来使得图片放大缩小,然后再通过改变box的locaton使得光标位置不变。具体算法就是基本的数学运算了,通过相似三角形求的locaton应该移动的向量,做出位置改变。
void pictureBox1_MouseWheel(object sender, MouseEventArgs e)//鼠标滚轮事件
{
double step = 1.2
if (e.Delta > 0)
{
if (pictureBox1.Height >= Screen.PrimaryScreen.Bounds.Height*10)
return
pictureBox1.Height = (int)(pictureBox1.Height * step)
pictureBox1.Width = (int)(pictureBox1.Width * step)
int px = Cursor.Position.X - pictureBox1.Location.X
int py = Cursor.Position.Y - pictureBox1.Location.Y
int px_add = (int)(px * (step - 1.0))
int py_add = (int)(py * (step - 1.0))
pictureBox1.Location = new Point(pictureBox1.Location.X - px_add, pictureBox1.Location.Y - py_add)
Application.DoEvents()
}
else
{
if (pictureBox1.Height <= Screen.PrimaryScreen.Bounds.Height)
return
pictureBox1.Height = (int)(pictureBox1.Height / step)
pictureBox1.Width = (int)(pictureBox1.Width / step)
int px = Cursor.Position.X - pictureBox1.Location.X
int py = Cursor.Position.Y - pictureBox1.Location.Y
int px_add = (int)(px * (1.0 - 1.0 / step))
int py_add = (int)(py * (1.0 - 1.0 / step))
pictureBox1.Location = new Point(pictureBox1.Location.X + px_add, pictureBox1.Location.Y + py_add)
Application.DoEvents()
}
}