LEADTOOLS includes more than 30 built-in annotation objects that can be extended to create custom annotation objects. This tutorial demonstrates how to create a custom circle annotation derived from the AnnEllipseObject
class, as well as create a custom freehand annotation with a key modifier funtionality by extending the AnnFreehandDesigner
class, in a C# WinForms application using the Image Viewer.
Overview | |
---|---|
Summary | This tutorial covers both the automated and custom annotation features in a C# WinForms application using the Image Viewer. |
Completion Time | 45 minutes |
Visual Studio Project | Download tutorial project (13 KB) |
Platform | WinForms C# Application |
IDE | Visual Studio 2022 |
Development License | Download LEADTOOLS |
Try it in another language |
|
Before working on the Create a Custom Annotation - WinForms C# tutorial, get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial.
Start with a copy of the project created in the Add References and Set a License tutorial. If you do not have that project, follow the steps in that tutorial to create it.
The references needed depend upon the purpose of the project. References can be added by one or the other of the following two methods (but not both). For this project, the following references are needed:
If using NuGet references, this tutorial will require the following NuGet packages:
Leadtools.Annotations.WinForms
Leadtools.Viewer.Controls.WinForms
If local DLL references are used, the following DLLs are needed. The DLLs are located at <INSTALL_DIR>\LEADTOOLS23\Bin\net
:
Leadtools.dll
Leadtools.Annotations.Automation.dll
Leadtools.Annotations.Designers.dll
Leadtools.Annotations.Engine.dll
Leadtools.Annotations.Rendering.WinForms.dll
Leadtools.Annotations.WinForms.dll
Leadtools.Controls.WinForms.dll
Leadtools.Core.dll
For a complete list of which DLL files are required for your application, refer to Files to be Included in your Application.
The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details including tutorials for different platforms, refer to Setting a Runtime License.
There are two types of runtime licenses:
Note: Adding LEADTOOLS NuGet and local references and setting a license are covered in more detail in Add References and Set a License.
With the project created, the references added, and the license set, coding can begin. Right-click on Form1.cs
in the Solution Explorer, and select View Code to bring up the code behind the form. Add the below code in the Using block and declare global members.
using Leadtools;
using Leadtools.Controls;
using Leadtools.Annotations.Engine;
using Leadtools.Annotations.Automation;
using Leadtools.Annotations.Designers;
using Leadtools.Annotations.Rendering;
using Leadtools.Annotations.WinForms;
private ImageViewer _imageViewer;
private AutomationInteractiveMode _annInteractiveMode;
private IAnnAutomationControl _automationControl;
private AnnAutomationManager _annManager;
private AnnAutomation _annAutomation;
In the Solution Explorer, double-click Form1.cs
to display it in the designer, and click on the Events icon in the Properties Windows. Then, double-click the Load event to create an event handler if one does not already exist.
Add the following code inside the Form1_Load
event handler to initialize the ImageViewer, create a new blank RasterImage, and set it in the viewer.
private void Form1_Load(object sender, EventArgs e)
{
// Initialize the imageViewer object
_imageViewer = new ImageViewer();
_imageViewer.Dock = DockStyle.Fill;
_imageViewer.BackColor = Color.DarkGray;
Controls.Add(_imageViewer);
_imageViewer.BringToFront();
// Create a plain white background to draw on
_imageViewer.Image = RasterImage.Create(1000, 1000, 24, 96, RasterColor.White);
}
In the Solution Explorer, right-click the project file -> Properties
In the properties menu go to Resources -> Create or open assembly sources
Click Add Resource and then click Add Existing File....
Download the Circle Icon PNG image below and browse to the location and click Open.
After the resource has been imported, the project will create a Resources
folder.
This image needs to be embedded into the project. To do so, navigate to Solution Explorer, drop down the Resources
folder, and click on Create-a-Custom-Annotation-Circle-Icon.png
. In the properties, change Build Action to embedded resource.
In the Solution Explorer, right-click the Project, highlight Add, and click Create Folder. Rename the folder to be AnnCircleObject
.
In the Solution Explorer, right-click the AnnCircleObject
folder, highlight Add, and click Class....
Add three new classes:
AnnCircleDrawDesigner.cs
AnnCircleObject.cs
AnnCircleObjectRenderer.cs
Note: Be sure to change the namespace for each of these classes to match the namespace in Form1.cs
.
Add the below code to the AnnCircleDrawDesigner
class:
using System;
using Leadtools;
using Leadtools.Annotations.Engine;
using Leadtools.Annotations.Designers;
namespace Create_a_Custom_Annotation
{
class AnnCircleDrawDesigner : AnnRectangleDrawDesigner
{
//We need 2 points, a beginning and an ending point
private LeadPointD begin = LeadPointD.Empty;
private LeadPointD end = LeadPointD.Empty;
/// <summary>
/// Constructor for the AnnCircleDrawDesigner
/// </summary>
public AnnCircleDrawDesigner(IAnnAutomationControl automationControl, AnnContainer container, AnnCircleObject annObject)
: base(automationControl, container, annObject) { }
/// <summary>
/// override the pointer down event
/// set the beginning and ending points to the location of the first click
/// </summary>
public override bool OnPointerDown(AnnContainer sender, AnnPointerEventArgs e)
{
begin = e.Location;
end = begin;
return base.OnPointerDown(sender, e);
}
/// <summary>
/// override the pointer move event
/// set the new mouse point to the end variable
/// do some math to create a circle object (width/height stay equal)
/// </summary>
public override bool OnPointerMove(AnnContainer sender, AnnPointerEventArgs e)
{
end = e.Location;
AnnCircleObject circle = (AnnCircleObject)TargetObject;
double x = (end.X - begin.X);
double y = Math.Abs(end.Y - begin.Y);
double scaleX = 1;
double scaleY = 1;
if (x < y)
scaleX = y / x;
else
scaleY = x / y;
circle.Rect = LeadRectD.Create(begin.X, begin.Y, Math.Abs(end.X - begin.X) * Math.Abs(scaleX), Math.Abs(end.Y - begin.Y) * Math.Abs(scaleY));
Invalidate(LeadRectD.Empty);
return true;
}
}
}
Add the below code to the AnnCircleObject
class:
using Leadtools.Annotations.Engine;
namespace Create_a_Custom_Annotation
{
class AnnCircleObject : AnnEllipseObject
{
//set the id to the UserObjectID
public const int CircleObjectId = UserObjectId;
/// <summary>
/// Constructor for the object
/// set the id of the object to the circle object ID
/// </summary>
public AnnCircleObject()
: base()
{
SetId(CircleObjectId);
Tag = null;
}
protected override AnnObject Create()
{
return new AnnCircleObject();
}
}
}
Add the below code to the AnnCircleObjectRenderer
class:
using System.Collections.Generic;
using Leadtools.Annotations.Rendering;
using Leadtools.Annotations.Automation;
using Leadtools.Annotations.Engine;
using Leadtools;
namespace Create_a_Custom_Annotation
{
class AnnCircleObjectRenderer : AnnEllipseObjectRenderer
{
/// <summary>
/// Constructor for the renderer
/// get the ellipse object renderer and use the same styles for the circle
/// </summary>
public AnnCircleObjectRenderer(AnnAutomationManager manager)
: base()
{
IAnnObjectRenderer annEllipseObjRenderer = manager.RenderingEngine.Renderers[AnnObject.EllipseObjectId];
LabelRenderer = annEllipseObjRenderer.LabelRenderer;
LocationsThumbStyle = annEllipseObjRenderer.LocationsThumbStyle;
RotateCenterThumbStyle = annEllipseObjRenderer.RotateCenterThumbStyle;
RotateGripperThumbStyle = annEllipseObjRenderer.RotateGripperThumbStyle;
// The below snippet changes the annotation's thumbnail size
//LeadSizeD newThumbSize = LeadSizeD.Create(300, 300); // New size of the thumbnails, change as necessary
//LocationsThumbStyle.Size = newThumbSize;
//RotateCenterThumbStyle.Size = newThumbSize;
//RotateGripperThumbStyle.Size = newThumbSize;
}
/// <summary>
/// override the RenderThumbs method
/// go through the thumbs and remove the top bottom left and right thumbs so it cannot be changed from a circle
/// </summary>
public override void RenderThumbs(AnnContainerMapper mapper, LeadPointD[] thumbLocations, AnnFixedStateOperations operations)
{
List<LeadPointD> newThumbs = new List<LeadPointD>();
for (int i = 0; i < thumbLocations.Length; i += 2)
newThumbs.Add(thumbLocations[i]);
base.RenderThumbs(mapper, newThumbs.ToArray(), operations);
}
}
}
As before when creating the custom Circle annotation classes, open the Solution Explorer
, right-click the Project
, highlight Add
, and click Create Folder
. Rename the folder to be Customization
.
In the Solution Explorer, right-click the Customization
folder, highlight Add, and click Class....
Add the new class:
- MyAnnFreehandDrawDesigner.cs
Add the following code to the MyAnnFreehandDrawDesigner
class:
using System;
using Leadtools;
using Leadtools.Annotations.Engine;
using Leadtools.Annotations.Designers;
namespace Create_a_Custom_Annotation
{
class MyAnnFreehandDrawDesigner : AnnFreehandDrawDesigner
{
/// <summary>
/// Constructor for the AnnFreehandDrawDesigner
/// </summary>
public MyAnnFreehandDrawDesigner(IAnnAutomationControl annAutomationControl, AnnContainer container, AnnPolylineObject annPolylineObject)
: base(annAutomationControl, container, annPolylineObject) { }
/// <summary>
/// override the pointer move event
/// add key modifier when pressing shift
/// </summary>
public override bool OnPointerMove(AnnContainer sender, AnnPointerEventArgs e)
{
// Only draw when holding "LMB"
if (base.TargetObject == null || base.IsMouseLeftButtonDown != true)
return false;
AnnPolylineObject polyline = (AnnPolylineObject)base.TargetObject;
// Draw staight lines
if (this.IsExtendedMode) // Detect pressing "Shift"
{
polyline.Points.RemoveAt(polyline.Points.Count - 1);
polyline.Points.Add(ClipPoint(e.Location, ClipRectangle));
Working();
return true;
}
return base.OnPointerMove(sender, e);
}
}
}
The AnnFreehandDrawDesigner
Designer class that MyAnnFreehandDrawDesigner
inherits from has a property to detect whether the "Shift" key is held called IsExtendedMode
. By utilizing this property in the overridden OnPointerMove()
function, we can add alternate functionality when the user is holding the "Shift" key.
Right-click on Form1.cs
in the Solution Explorer and select View Code to bring up the code behind the form. Add a new method, name it InitAnnotations()
, and call the new method inside the Form1_Load
event handler below imageViewer.BringToFront()
.
private void Form1_Load(object sender, EventArgs e)
{
// Initialize the imageViewer object
_imageViewer = new ImageViewer();
_imageViewer.Dock = DockStyle.Fill;
_imageViewer.BackColor = Color.DarkGray;
Controls.Add(_imageViewer);
_imageViewer.BringToFront();
InitAnnotations();
// Create a plain white background to draw on
_imageViewer.Image = RasterImage.Create(1000, 1000, 24, 96, RasterColor.White);
// Initialize the codecs object.
_codecs = new RasterCodecs();
}
Add the following code inside the InitAnnotations()
method:
void InitAnnotations()
{
try
{
// AnnManager initialization comes first
_annManager = new AnnAutomationManager();
_annManager.RestrictDesigners = true;
_annManager.RenderingEngine = new AnnWinFormsRenderingEngine();
// Create my custom objects
_annManager.Objects.Add(CreateCircleAutomationObject());
_annManager.Objects.Add(CreateFreehandAutomationObject());
// Update Rendering engine for the circle
_annManager.RenderingEngine.Renderers.Add(AnnCircleObject.CircleObjectId, new AnnCircleObjectRenderer(_annManager));
// Create the helper and toolbar, then add them to the form
AutomationManagerHelper annHelper = new AutomationManagerHelper(_annManager);
annHelper.CreateToolBar();
Controls.Add(annHelper.ToolBar);
// Create the automation control and attach the viewer to it
_automationControl = new ImageViewerAutomationControl();
((ImageViewerAutomationControl)_automationControl).ImageViewer = _imageViewer;
// Initialize the interactive mode and add it to the viewer
_annInteractiveMode = new AutomationInteractiveMode();
_annInteractiveMode.AutomationControl = _automationControl;
_imageViewer.InteractiveModes.BeginUpdate();
_imageViewer.InteractiveModes.Add(_annInteractiveMode);
_imageViewer.InteractiveModes.EndUpdate();
// Initialize the automation
annAutomation = new AnnAutomation(_annManager, _automationControl);
// Whenever loading a new image, set the new size in the container
_imageViewer.ItemChanged += ImageViewer_ItemChanged;
annAutomation.Active = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void ImageViewer_ItemChanged(object sender, ImageViewerItemChangedEventArgs e)
{
if (e.Reason == ImageViewerItemChangedReason.Image)
_annAutomation.Container.Size = _annAutomation.Container.Mapper.SizeToContainerCoordinates(_imageViewer.ImageSize.ToLeadSizeD());
}
Add a new method to create the custom Circle annotation automation object inside the Form1
class named CreateCircleAutomationObject()
that returns an AnnAutomationObject
. This method is called inside the InitAnnotations()
method as shown above. Add the below code to the new method:
private AnnAutomationObject CreateCircleAutomationObject()
{
// Create the circle object, assign the designers, set the toolbar image, and then return the new object
AnnAutomationObject circleAutomationObject = new AnnAutomationObject();
circleAutomationObject.Id = AnnCircleObject.CircleObjectId;
circleAutomationObject.Name = "Circle";
circleAutomationObject.ToolBarToolTipText = circleAutomationObject.Name;
circleAutomationObject.DrawDesignerType = typeof(AnnCircleDrawDesigner);
circleAutomationObject.EditDesignerType = typeof(AnnRectangleEditDesigner);
circleAutomationObject.RunDesignerType = typeof(AnnRunDesigner);
circleAutomationObject.ObjectTemplate = new AnnCircleObject();
circleAutomationObject.ToolBarImage = Properties.Resources.CircleIcon;
return circleAutomationObject;
}
Next, add a new method to create the custom Freehand annotation automation object inside the Form1
class named CreateFreehandAutomationObject()
that returns an AnnAutomationObject. This method is likewise called inside the InitAnnotations()
method as shown above. Add the below code to the new method:
private AnnAutomationObject CreateFreehandAutomationObject()
{
// Create the freehand object, assign the designers, set the toolbar image, and then add return the new object
AnnAutomationObject freehandAutomationObject = new AnnAutomationObject();
freehandAutomationObject.Id = AnnObject.FreehandObjectId;
freehandAutomationObject.Name = "Freehand";
freehandAutomationObject.ToolBarToolTipText = freehandAutomationObject.Name;
freehandAutomationObject.DrawDesignerType = typeof(MyAnnFreehandDrawDesigner);
freehandAutomationObject.EditDesignerType = typeof(AnnPolylineEditDesigner);
freehandAutomationObject.RunDesignerType = typeof(AnnRunDesigner);
freehandAutomationObject.UseRotateThumbs = true;
freehandAutomationObject.ObjectTemplate = new AnnPolylineObject();
return freehandAutomationObject;
}
Run the project by pressing F5, or by selecting Debug -> Start Debugging.
If the steps were followed correctly, the application should run and display a blank white RasterImage. To draw the custom annotations, click their corresponding buttons in the top left corner of the window. While the freehand annotation is selected, the "Shift" key can be held to force the drawing to be a straight line until the button is let go.
This tutorial covered how to create a custom circle & freehand annotations using the LEADTOOLS Annotations SDK technology.