Create a Custom Annotation - WinForms C#

This tutorial demonstrates how to create a WinForms C# application to create a custom annotation using the LEADTOOLS SDK.

Overview  
Summary This tutorial demonstrates how to use LEADTOOLS custom annotation technology in a C# WinForms Application.
Completion Time 45 minutes
Visual Studio Project Download tutorial project (13 KB)
Platform WinForms C# Application
IDE Visual Studio 2017, 2019
Development License Download LEADTOOLS
Try it in another language
  • C#: .NET Framework (WinForms), WPF

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

Create a new C# Windows Winforms project, and add the below necessary LEADTOOLS references.

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>\LEADTOOLS21\Bin\Dotnet4\x64:

For a complete list of which Codec DLLs are required for specific formats, refer to File Format Support.

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, drop down the Properties tab, and double-click Resources.resx.

Open Resource File

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> 
        /// Contstructor 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.Create-a-Custom-Annotation-Circle-Icon.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 21.0.2023.3.1
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2021 LEAD Technologies, Inc. All Rights Reserved.

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