DrawingView: Simple Generic Winform 2D Drawing Component






4.75/5 (6 votes)
2D Drawing component with Scaling, Zooming, Scrolling, Centering and Resizing capabilities
Introduction
Simple generic WinForm
2D drawing components with scaling, zooming, scrolling, centering and resizing is not so easy to find. In CodeProject, there are a lot of publications relative to this subject but they are all specific to projects, coded for WPF or in C++. Many are for Picture resizing and zooming, but few for simple WinForm
2D drawing. This project uses a simple PictureBox
to manage the drawing, so it is not necessary to have a lot of code behind.
How It Works
The DrawingWindow
component is a simple UserControl
with a PictureBox
inside. The PictureBox
contains a bitmap which is filled with a user drawing callback event. The size of the bitmap, the background color, scale, zoom factor and margins are all properties of the control. The coordinate system is referenced at the lower-left corner taking account of the margins. The bitmap is positioned in the control according to scale, zoom factor and scrolling position.
Using the Code
To use the DrawingWindow UserControl
, simply put it inside a Form
or another UserControl
, set the properties and connect the events.
The Properties
In this example, the DrawingSize
is A4 format, 210 mm x 297 mm. The initial ZoomFactor
is set to 2
.
To Zoom In or Out, simply set the ZoomFactor
to another value like this.
DrawClientCenterPoint
property is used for debugging only!
/// Zoom In
drawingWindow.ZoomFactor *= 2;
/// Zoom Out
drawingWindow.ZoomFactor /= 2;
The Events
/// 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;
The DrawingPaint
event is the callback to draw. The PaintEventArgs
is the same as standard paint events. It contains the Graphics
object sets with a matrix translation according to the rectangle you define, i.e., (210;297) in this example.
The Methods
/// 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);
The ResizeDrawing
function has a parameter resize
(true
/false
) telling the component to resize always when the client rectangle is resizing.
History
- 21st October, 2022: Initial version