winform picturebox流畅移动缩放给出代码
时间: 2023-09-16 18:12:39 浏览: 96
C# winform控件的拖动和缩放
3星 · 编辑精心推荐
以下是Winform PictureBox流畅移动缩放的代码示例:
private Point _ptOriginal = new Point(); //存储起始点
private Point _ptLast = new Point(); //存储拖动过程中的上一个点
private bool _bDragging = false; //是否拖动中
private double _scale = 1.0; //缩放比例
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (!_bDragging)
{
_bDragging = true;
_ptOriginal = e.Location;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (_bDragging)
{
_ptLast = e.Location;
int dx = _ptLast.X - _ptOriginal.X;
int dy = _ptLast.Y - _ptOriginal.Y;
pictureBox1.Left += dx;
pictureBox1.Top += dy;
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
_bDragging = false;
}
private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
{
double scale = 1 + (e.Delta * SystemInformation.MouseWheelScrollLines / 1200.0);
if (_scale * scale > 0.1 && _scale * scale < 10) //限制缩放比例
{
_scale *= scale;
pictureBox1.Width = (int)(_scale * pictureBox1.Image.Width);
pictureBox1.Height = (int)(_scale * pictureBox1.Image.Height);
Point p = pictureBox1.PointToClient(Control.MousePosition);
int dx = (int)(p.X * scale - p.X);
int dy = (int)(p.Y * scale - p.Y);
pictureBox1.Left -= dx;
pictureBox1.Top -= dy;
}
}
在这个示例中, _ptOriginal 存储了PictureBox的起始点,_ptLast 存储了PictureBox拖动过程中的上一个点,_bDragging 表示PictureBox是否正在被拖动,_scale 表示缩放比例。PictureBox的拖动操作通过pictureBox1_MouseDown、pictureBox1_MouseMove 和pictureBox1_MouseUp事件来实现,缩放操作是通过pictureBox1_MouseWheel事件来实现的。在PictureBox的MouseMove事件中,首先判断PictureBox是否正在被拖动,如果是,则根据拖动的过程中的位置差计算新位置。在PictureBox的MouseUp事件中,将_bDragging 标识设置为 false 表示PictureBox停止了拖动。在PictureBox的MouseWheel事件中,首先根据鼠标滚轮滚动的幅度计算缩放比例 scale,然后判断新的缩放比例是否在限制范围内,如果是,则根据缩放比例重新设置PictureBox的大小,并且根据鼠标的位置重新计算PictureBox的位置。
阅读全文