DrawingView:简单的通用 Winform 2D 绘图组件






4.75/5 (6投票s)
具有缩放、缩放、滚动、居中和调整大小功能的 2D 绘图组件
引言
寻找具有缩放、缩放、滚动、居中和调整大小功能的简单通用 WinForm
2D 绘图组件并不容易。在 CodeProject 上,有很多关于这个主题的出版物,但它们都特定于项目,为 WPF 或 C++ 编写。 许多是用于图片调整大小和缩放,但很少用于简单的 WinForm
2D 绘图。 该项目使用一个简单的 PictureBox
来管理绘图,因此不需要大量的后台代码。
工作原理
DrawingWindow
组件是一个简单的 UserControl
,其中包含一个 PictureBox
。 PictureBox
包含一个位图,该位图通过用户绘图回调事件填充。 位图的大小、背景颜色、缩放比例、缩放因子和边距都是控件的属性。 坐标系参考位于左下角,并考虑了边距。 位图根据缩放比例、缩放因子和滚动位置放置在控件中。
Using the Code
要使用 DrawingWindow UserControl
,只需将其放在 Form
或另一个 UserControl
中,设置属性并连接事件即可。
属性
在此示例中,DrawingSize
为 A4 格式,即 210 毫米 x 297 毫米。 初始 ZoomFactor
设置为 2
。
要放大或缩小,只需将 ZoomFactor
设置为另一个值即可,如下所示。
DrawClientCenterPoint
属性仅用于调试!
/// Zoom In
drawingWindow.ZoomFactor *= 2;
/// Zoom Out
drawingWindow.ZoomFactor /= 2;
事件
/// This is called to paint the drawing
public EventHandler<PaintEventArgs> DrawingPaint;
/// This is called when the mouse moves over the drawing
public EventHandler<MouseEventArgs> DrawingMouseMove;
DrawingPaint
事件是回调以进行绘图。 PaintEventArgs
与标准的绘制事件相同。 它包含根据您定义的矩形(例如,此示例中的 (210;297))设置矩阵转换的 Graphics
对象。
方法
/// Redraw the drawing
public void Redraw();
/// Center the drawing into the client rectangle
public void Center();
/// Resize the drawing according to the client rectangle
public void ResizeDrawing(bool resize);
/// Get the image with a defined zoom factor (to save or print)
public Image GetImage(float zoomFactor, Rectangle bounce);
ResizeDrawing
函数有一个参数 resize
(true
/false
),它告诉组件在客户端矩形调整大小时始终调整大小。
历史
- 2022 年 10 月 21 日:初始版本