目录
介绍
具有缩放、缩放、滚动、居中和调整大小的简单通用WinForm 2D绘图组件并不容易找到。在CodeProject中,有很多与此主题相关的出版物,但它们都特定于项目,为WPF或C++编码。许多用于图片大小调整和缩放,但很少用于简单的WinForm 2D绘图。这个项目使用简单的PictureBox来管理绘图,所以没有必要背后有很多代码。
工作原理
该DrawingWindow组件是一个在其内部使用PictureBox的简单的UserControl。PictureBox包含填充有用户绘制回调事件的位图。位图的大小、背景色、比例、缩放系数和边距都是控件的属性。参照左下角的坐标系,同时考虑边距。位图根据比例、缩放系数和滚动位置在控件中定位。
使用代码
要使用DrawingWindow UserControl,只需将其放入Form或另一个UserControl,设置属性并连接事件。
属性
在本例中,DrawingSize为A4格式,210毫米x297毫米。初始的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与标准绘制事件相同。它包含根据您定义的矩形进行矩阵平移的Graphics对象集,即本例中的 (210;297)。
方法
/// 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),告知组件在客户端矩形调整大小时始终调整大小。
https://www.codeproject.com/Articles/5345054/DrawingView-Simple-Generic-Winform-2D-Drawing-Comp