Create a Custom Annotation - WinForms C#

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 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 (3 KB)
Platform WinForms C# Application
IDE Visual Studio 2022
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

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.

Create the Project and Add LEADTOOLS References

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:

If local DLL references are used, the following DLLs are needed. The DLLs are located at <INSTALL_DIR>\LEADTOOLS22\Bin\net:

For a complete list of which DLL files are required for your application, refer to Files to be Included in your Application.

Set the License File

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.

Initialize the Image Viewer

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.

C#
// Using block at the top 
using System; 
using System.Drawing; 
using System.Windows.Forms; 
using Leadtools; 
using Leadtools.Codecs; 
using Leadtools.Controls; 
using Leadtools.Annotations.Engine; 
using Leadtools.Annotations.Automation; 
using Leadtools.Annotations.Designers; 
using Leadtools.Annotations.Rendering; 
using Leadtools.Annotations.WinForms; 
C#
// Declare these global members 
private ImageViewer _imageViewer; 
private RasterCodecs _codecs; 
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.

Create a Load event

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.

C#
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); 
 
    // Initialize the codecs object. 
    codecs = new RasterCodecs(); 
} 

Add Toolbar Icon Resource

In the Solution Explorer, right-click the project file -> Properties

Open properties

In the properties menu go to Resources -> Create or open assembly sources

Open resources

Click Add Resource and then click Add Existing File....

Add Existing Item

Download the Circle Icon PNG image below and browse to the location and click Open.

Circle Icon

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.

Embed Custom Annotation Resource

Create Custom Circle Annotation Object Classes

In the Solution Explorer, right-click the Project, highlight Add, and click Create Folder. Rename the folder to be AnnCircleObject.

Create Circle Object Folder

In the Solution Explorer, right-click the AnnCircleObject folder, highlight Add, and click Class....

Add Class

Add three new classes:

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:

C#
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:

C#
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:

C#
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); 
        } 
    } 
} 

Initialize Annotations and Create Custom Annotation Code

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().

C#
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:

C#
void InitAnnotations() 
 { 
    //AnnManager initialization comes first 
    _annManager = new AnnAutomationManager(); 
    _annManager.RestrictDesigners = true; 
    _annManager.RenderingEngine = new AnnWinFormsRenderingEngine(); 
 
    //Create my custom objects  
    CreateCustomObject(_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; 
} 
 
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 inside the Form1 class named CreateCustomObject(AnnAutomationManager annManager). This method is called inside the InitAnnotations() method as shown above. Add the below code to the new method:

C#
private void CreateCustomObject(AnnAutomationManager _annManager) 
{ 
    //create the circle object, assign the designers, set the toolbar image, and then add it to the manager and rendering engine 
    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 = new Bitmap(typeof(Form1), "Resources.Dotnet-WinForms-Create-a-Custom-Annotation-Circle.png"); 
    circleAutomationObject.ContextMenu = new Leadtools.Annotations.WinForms.ObjectContextMenu(); 
    _annManager.Objects.Add(circleAutomationObject); 
    _annManager.RenderingEngine.Renderers.Add(AnnCircleObject.CircleObjectId, new AnnCircleObjectRenderer(_annManager)); 
} 

Run the Project

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 circle annotations, click the button on the top left of the form.

Final Result

Wrap-up

This tutorial covered how to create a custom circle annotation using the LEADTOOLS Annotations SDK technology.

See Also

Help Version 22.0.2024.2.20
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.


Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.