本文介紹一個針對 .NET 桌面應用程序的獨立圖片縮放拖拽顯示控件?SQPhoto[1]。
SQPhoto 是一個 Windows 桌面應用的組件,支持 .NET6 和 .NET Framework 4.6 + 。基于 PictureBox 的圖片展示工具,增加了拖動和縮放功能,便于在某些場景下的圖片展示,比如我前面開發的?Snipping_OCR[2]?工具就使用了這個組件。

該用戶組件采用?Panel
?和?PictureBox
?組合的方式,控制?PictureBox
?在?Panel
?容器中顯示的位置和大小來實現拖拽和放大縮小的功能。
/// <summary>
/// 計算鼠標移動位置是否還在容器內
/// </summary>
/// <returns></returns>
private bool IsMouseInPanel()
{if (PanBox.Left < PointToClient(Cursor.Position).X&& PointToClient(Cursor.Position).X < PanBox.Left + PanBox.Width&& PanBox.Top < PointToClient(Cursor.Position).Y&& PointToClient(Cursor.Position).Y < PanBox.Top + PanBox.Height){return true;}else{return false;}
}/// <summary>
/// 鼠標移動
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PicBox_MouseMove(object sender, MouseEventArgs e)
{//開啟移動 左鍵按下 并且移動位置在框內if (_CanMove && isSelected && IsMouseInPanel()){PicBox.Location = new Point(PicBox.Left + (Cursor.Position.X - mouseDownPoint.X), PicBox.Top + (Cursor.Position.Y - mouseDownPoint.Y));mouseDownPoint = Cursor.Position;}
}
縮放的實現:
/// <summary>
/// 控制圖片縮放
/// </summary>
/// <param name="change">變化情況,大于 0 放大,小于 0 縮小</param>
public void PicZoomSize(int change)
{var t = PicBox.Size;t.Width += change;t.Height += change;//控制最小縮放if (t.Width < _ZoomMin) return;PicBox.Size = t;//圖片按中心比例放大縮小if (!_ZoomCenter) return;PicBox.Location = new Point((this.Width - PicBox.Width) / 2, (this.Height - PicBox.Height) / 2);
}

以上組件和 Demo 倉庫地址:https://github.com/sangyuxiaowu/SQPhoto
References
[1]
?SQPhoto:?https://www.nuget.org/packages/SQPhoto/[2]
?Snipping_OCR:?https://github.com/sangyuxiaowu/Snipping_OCR