Horizontal Full Bar Chart in JavaScript

We use here MindFusion JavaScript library for Charts and Gauges to build this horizontal stacked bar chart that renders custom tooltips:

Run the sample from this link.

You can download the source code together with the libraries used from the link at the bottom of the post.

I. General Setup

We split our chart in two files – one is the web page that hosts an HTML Canvas element that will render the chart. The other file is a JavaScript code-behind file that contains the code for the chart.

We need to add reference to two JavaScript library files that provide the charting and drawing functionality that we need:

MindFusion.Common.js
MindFusion.Charting.js

We place them in a Scripts folder at the same level as our web page and JavaScript code behind file.

<script type="text/javascript" src="Scripts/MindFusion.Common.js"></script>
<script type="text/javascript" src="Scripts/MindFusion.Charting.js"></script>

We also add a reference to the code-behind file that we call StackedBarChart.js:

<script type="text/javascript" src="StackedBarChart.js"></script>

Now we need to create an HTML Canvas element and we must provide it with an id so we can reference it in our JS code:

<canvas id="barChart" width="600px" height="400px"></canvas>

The size of the Canvas determines the size of the chart.

II. Chart Instance and General Settings

We add some namespace mappings that allow us to reference classes from the Chart library in a more consice manner:

var Charting = MindFusion.Charting;
var Controls = MindFusion.Charting.Controls;
var Collections = MindFusion.Charting.Collections;
var Drawing = MindFusion.Charting.Drawing;
var GridType = MindFusion.Charting.GridType;
var ToolTip = Charting.ToolTip;

Then we create an instance of the BarChart control. We need to get the Dom Element that corresponds to the Canvas that we’ve prepared for the chart:

var chartEl = document.getElementById('barChart');
chartEl.width = chartEl.offsetParent.clientWidth;
chartEl.height = chartEl.offsetParent.clientHeight;
var chart = new Controls.BarChart(chartEl, Charting.BarLayout.Stack);

The BarChart constructor supports a second argument that indicates the type of the bar chart to render.

We set the bar chart to horizontal with the horizontalBars property. We also make the bars thicker than normal – the property for this is barSpacingRatio It measures the thickness of the bars as a percente of the bar width.

chart.horizontalBars = true;
chart.barSpacingRatio = 0.2;

III. The Data Series

We want our chart to render labels as tooltips, inside the bars and also we want custom labels at the Y-axis. The predefined BarSeries class accepts 4 lists with data: one for bar data and three with labels inside the bars, at the top of the bars and at the X-axis. So, it is not an exact match for what we want to do and we need to customize it.

We will create our own custom BarSeries that we will call SeriesWithLabels. We will inherit the BarSeries class and override its constructor and getLabel members to provide the desired data for the desired type of labels.

We override the constructor by creating three new variables, which receive the data for the bars and the labels:

var SeriesWithLabels = function (barValues, innerLabels, yLabels) {
    Charting.BarSeries.apply(this, [barValues, innerLabels, yLabels]);
	
	this.yLabels = yLabels;
	this.innerLabels = innerLabels;
	this.values = barValues;
    
};

SeriesWithLabels.prototype = Object.create(Charting.BarSeries.prototype);

Note that before we do anything else in the new constructor we need to call the apply method of the BarSeries class to transfer the provided data to the base class. We also need to create a prototype of the new series and also define its constructor:

 Object.defineProperty(SeriesWithLabels.prototype, 'constructor', {
   	value: SeriesWithLabels,
   	enumerable: false,
   	writable: true
   });

Next we will override the getLabel method. This is the method that returns the correct label according to the requested label kind and the index of the label. We said we want to support inner labels, tooltips and Y-axis labels. So, we make sure our implementation of getLabel returns exactly those labels:

SeriesWithLabels.prototype.getLabel = function (index, kind) {
    if ((kind & Charting.LabelKinds.YAxisLabel) != 0 && this.yLabels)
        return this.yLabels.items()[index];

    if ((kind & Charting.LabelKinds.InnerLabel) != 0 && this.innerLabels)
        return this.innerLabels.items()[index];
	
	if ((kind & Charting.LabelKinds.ToolTip) != 0)
        return getPercentLabel(index, this);
   
    return "";
};

Getting the correct inner and top label is easy – we just return the label at the requested position. What is more work is building the tooltip. We want our tooltip to calculate the portion of the part in the stacked bar the mouse currently is over, to the entire bar. This means we need to calculate the data of all bar portions, which is a combination of the values at the requested position in all three bar series. We do this calculation in a separate method called getPercentLabel.

Before we get to the getPercentLabel method let’s create 3 instances of our custom SeriesWithLabels class:

var labels = new Collections.List([
	"POSITION", "SALARY", "LOCATION", "COLLEAGUES", "WORKTIME"
]);

// create sample data series
var series1 = new SeriesWithLabels(new Collections.List([123, 212, 220, 115, 0.01]), new Collections.List([123, 212, 220, 115, 0]), labels);
var series2 = new SeriesWithLabels(new Collections.List([53, 132, 42, 105, 80]), new Collections.List([53, 132, 42, 105, 80]), null);
var series3 = new SeriesWithLabels(new Collections.List([224, 56, 138, 180, 320]), new Collections.List([224, 56, 138, 180, 320]), null);

The third argument in the SeriesWithLabels constructor is the lists with labels at the Y-axis. We need just one list with labels and we set it with the first series. The other series take null as their third argument.

We need to create a collection with the series and assign it to the series property of the chart:

var series = new Collections.ObservableCollection(new Array(series1, series2, series3));
chart.series = series;

There is a special property called supportedLabels that is member of Series and tells the chart, what type of labels this Series needs to draw. In our case we need to indicate that the first series renders labels at the Y-axis, the inner labels and tooltips. The other two series render inner labels and tooltips:

series1.supportedLabels = Charting.LabelKinds.YAxisLabel | Charting.LabelKinds.InnerLabel | Charting.LabelKinds.ToolTip;
series2.supportedLabels = Charting.LabelKinds.InnerLabel | Charting.LabelKinds.ToolTip;
series3.supportedLabels = Charting.LabelKinds.InnerLabel | Charting.LabelKinds.ToolTip;

Now let’s get back to the method that calculates the tooltip:

function getPercentLabel(index, series)
{
	var value1 = series1.values.items()[index];
	var value2 = series2.values.items()[index];
	var value3 = series3.values.items()[index];
	
	var theValue = series.values.items()[index];	
	var result = theValue/(value1+value2+value3) * 100;
	
	return Number(result).toFixed(0) + "%";	
};

In it we calculate the sum of all data that is rendered by the stacked bar at the specified index. Then we convert the data to percent and format it to have no numbers after the decimal point. That gives us a little inacurracy sometimes, when the value gets rounded to the next number and the sum of all percents actually is 101. You might want to change the formatting to toFixed(2) if you want to see the exact number rendered.

IV. Axes and Tooltip

By default the X-axis shows a title and both axes render the auto scale for the data of the chart. We need to hide the scale and we also hide the ticks that are rendered at the interval values:

chart.xAxis.title = "";
chart.yAxis.title = "";
chart.showXCoordinates = false;
chart.showYCoordinates = false;
chart.showXTicks = false;
chart.showYTicks = false;

We don’t want our chart to render axes at all, so we will draw them with the color of the chart background. You can also draw them with a transparent brush:

chart.theme.axisStroke = new Drawing.Brush(Drawing.Color.knownColors.White);

The tooltip renders automatically when the user hovers a bar. We can customize it with the properties of the static Tooltip class:

ToolTip.brush = new Drawing.Brush("#fafafa");
ToolTip.pen = new Drawing.Pen("#9caac6");
ToolTip.textBrush = new Drawing.Brush("#5050c0");
ToolTip.horizontalPadding = 6;
ToolTip.verticalPadding = 4;
ToolTip.horizontalOffset = 76;
ToolTip.verticalOffset = 34;
ToolTip.font = new Charting.Drawing.Font("Verdana", 12);

We add some padding to the tooltip text and increase its font size. We also render the tooltip with a little offset that will place it inside the bar, ater the inner label.

V. Styling and Legend

Styling o the charts is done through instances of SeriesStyle derived classes. The instance is assigned to the seriesStyle property of the Chart In our case we want to color each bar in three sections. That means the portion of the bar that corresponds to the same series is colored in the same color for all its members. That kind of styling is supported by the PerSeriesStyle class. It accepts a list with brushes and strokes and paints all elements of the series corresponding to the index of the brush in the list with this brush:

// create bar brushes
var thirdBrush = new Drawing.Brush("#97b5b5");
var secondBrush = new Drawing.Brush("#5a79a5");
var firstBrush = new Drawing.Brush("#003466");

// assign one brush per series
var brushes = new Collections.List([firstBrush, secondBrush, thirdBrush]);
chart.plot.seriesStyle = new Charting.PerSeriesStyle(brushes, brushes);

The theme property is the main property for styling the chart. The Theme class exposes fields for customizing the appearance of all chart elements. We first adjust the font and size of the axis labels – remember we have labels only at the Y-axis:

chart.theme.axisTitleFontSize = 14;
chart.theme.axisLabelsFontSize = 11;
chart.theme.axisTitleFontName = "Verdana";
chart.theme.axisLabelsFontName = "Verdana";
chart.theme.axisLabelsFontSize = 14;
chart.theme.axisStroke = new Drawing.Brush(Drawing.Color.knownColors.White);

The labels inside the bars are called data labels and there are dataLabels*** properties that regulate their appearance:

chart.theme.dataLabelsFontName = "Verdana";
chart.theme.dataLabelsFontSize = 14;
chart.theme.dataLabelsBrush = new Drawing.Brush("#ffffff");

The dataLabelsBrush is also used when the legend labels are rendered. In order to make them visible we need to set a darker background for the legend:

chart.theme.legendBackground = new Drawing.Brush("#cccccc");
chart.theme.legendBorderStroke = new Drawing.Brush("#cecece");

The labels inside the legend are taken from the title property of the Series instances:

series.item(0).title = "CAREER START";
series.item(1).title = "MIDDLE OF CAREER";
series.item(2).title = "CAREER END";

Finally we should not forget to call the draw method that actually renders the chart:

chart.draw();

With this our costimization of the chart is done. You can download the source code of the sample and the MindFusion JavaScript libraries used from this link:

Download the Horizontal Stacked Bar Chart Sample: Source Code and Libraries

About Charting for JavaScript: MindFusion library for interactive charts and gauges. It supports all common chart types including 3D bar charts. Charts can have a grid, a legend, unlimitd number of axes and series. Scroll, zoom and pan are supported out of the box. You can easily create your own chart series by implementing the Series interface.
The gauges library is part of Charting for JavaScript. It supports oval and linear gauge with several types of labels and ticks. Various samples show you how the implement the gauges to create and customize all popular gauge types: car dashboard, clock, thermometer, compass etc. Learn more about Charting and Gauges for JavaScript at https://mindfusion.eu/javascript-chart.html.

MindFusion Releases Xamarin Charts

MindFusion Xamarin Chart has been released with the complete set of features needed to create and customize a wide selection of charts. The control boasts a variety of chart types like radar, polar, line, bubble, bar, column, doughnut, step, scatter etc. Part of the library are also a dashboard component and a component for financial charts.

3D Xamarin Chart

3D Xamarin Chart

Each chart type exposes numerous options to be customized in order to answer fully the requirements of the user. The control is packed with many samples that demonstrate different aspects of a chart type and offer ready-to-use code. The API is documented in details, with helpful tutorials and guides.

The chart component supports flexible data interface, which allows any data source to be used as a provider of chart data as long as it implements the Series interface. Predefined are a set of the most common data sources like XML, numeric lists, DateTime values, SQL database fields.

The innovative approach to styling lets developers control each aspect of the chart’s looks. They can alter the styling on the tiniest elements or concentrate on the bigger picture and create a global theme which can be reused.

Xamarin Bubble Chart

Xamarin Bubble Chart

The component is free to try without feature restrictions for a period of 60 days. Each license includes 12 month upgrade subscription. You can find out more about MindFusion Xamarin chart component at http://mindfusion.eu/xamarin-chart.html

About MindFusion: MindFusion has provided quality software tools for thousands of organizations and individuals for over a decade. With focus on lean software design and excellent technical support, MindFusion has been preferred by many Fortune 500 companies and world-known names from all industries and fields of business. MindFusion programming components are easy to use, with plenty of options to be customized and make development much faster and successful.

MindFusion.WinForms Pack, 2016.R2

MindFusion suite of WinForms controls has just been released and boasts a variety of new features to make you build WinForms applications faster and easier. Here is a review of the new version:

MindFusion Chart Control MindFusion.Charting

New data model

Data that should be drawn in charts is read through an interface called Series, whose instances can be assigned to the Series properties of Chart and SeriesRenderer classes. You can implement this interface in your own model classes to avoid duplicating data. The library includes several pre-defined series classes that let you specify data via IList or array objects.

Different series types in a single plot

The new data model allows adding different series types to a single plot

New rendering model

Chart graphics are drawn inside Plot components by SeriesRenderer-derived objects. Each plot can contain multiple series renderers from same or different types. For example, you can draw area, line and bar graphics in same plot by adding AreaRenderer, LineRenderer and BarRenderer objects to its SeriesRenderers collection. Chart controls automatically generate a series renderer of appropriate type for their Series.

Dashboard

The Dashboard control can contain multiple plots, axes, legends, images, gauges and text blocks arranged in dynamic layout. Individual components can be added to dashboard’s default RootPanel or LayoutPanel containers, or for more complex layouts add intermediary panels such as GridPanel and StackPanel to the default ones. To show different types of chart graphics, add Plot2D to draw in 2D Cartesian coordinate system, Plot3D for 3D Cartesian system, and PolarPlot for polar coordinate system. To draw horizontal or vertical axes, add respectively XAxisRenderer and YAxisRenderer objects. To show gauges, add LinearGaugeRenderer or OvalGaugeRenderer, whose Gauge property contains the gauge model definition.

The new WinForms Chart has a built-in dashboard control.

The new WinForms Chart has a built-in dashboard control.

Print and export

The Dashboard control and Chart controls that derive from it expose Print and PrintPreview methods for printing on paper. Call the ExportImage and CreateImage methods to generate bitmap image of the dashboard. The ExportPdf method exports the chart to a PDF (Portable Document Format) file. The ExportSvg method exports the chart to an SVG (Scalable Vector Graphics) file.

Styling

Values of appearance properties can come from several places in the component hierarchy. SeriesRenderer-derived objects can use attributes from their local SeriesStyle, from plot’s SeriesStyle, or from the *Series properties in current Theme. Component classes use either their local properties or ones defined in the theme. By default, appearance properties in SeriesRenderer > and Component > classes have null values, which makes the drawing code use values from the theme.

A rich choice of styling options are available

A rich choice of styling options are available

MindFusion WebForms Diagrammer MindFusion.Diagramming

Free-form nodes

A FreeFormNode collects all points from users’ mouse or touch input and displays them as node’s outline. To let users draw free-form nodes interactively, set Behavior to DrawFreeForms or LinkFreeForms. Use the Points property of FreeFormNode to get or set outline points programmatically. If the Closed property is set, the node is drawn as a closed shape and its interior filled, or otherwise the node is drawn as a poly-line. If the distance between first and last points drawn by user is shorter than AutoCloseDistance, the node’s Closed property is automatically set to true.

Free form nodes are drawn with the mouse

Free form nodes: just draw the node with the mouse and the control understands the shape you want

LinkLabel edit events

LinkTextEditing and LinkTextEdited events are now raised also when the user edits a LinkLabel. The Label property of the respective event-arguments class identifies the LinkLabel that is being edited. Label is a null reference if the user is editing link’s Text value.

keyboard16x16MindFusion Virtual Keyboard

MindFusion Virtual Keyboard has been initially added to MindFusion Pack for WinForms.

The WinForms virtual keyboard control: extended layout

The WinForms virtual keyboard control: extended layout

WPF Reporting ToolMindFusion.Reporting

Improved charts
MindFusion.Reporting now uses the new MindFusion charting engine to display charts in reports. The presentation of the charts has been greatly improved (particularly when resizing the charts).

Pie charts in a WinForms report

Pie charts in a WinForms report

Spreadsheet-16x16MindFusion.Spreadsheet

New and improved charts
MindFusion.Spreadsheet now uses the new MindFusion charting engine to display charts in worksheets. Along with the improved appearance (particularly when resizing the charts), the following new features have been added:

  • New Candlestick chart type;
  • New BarOverlayed and ColumnOverlayed chart types;
  • Several new legend position types;

Zoom
The worksheets can now be zoomed in and out through the new Zoom property.

Charts in a spreadsheet

The new chart engine makes spreadsheets even more appealing

MindFusion clients can download the installer for the latest version from the clients area on MindFusion website.

A direct link to download the WinForms pack is available from here:

Download MindFusion WinForms Pack 2016.R2

Updated assemblies are also available as MindFusion.Pack NuGet package.

About MindFusion.WinForms Pack: A rich set of programming components that provide WinForms developers with the complete list of features to build even the most complicated business applications fast and easy. The components integrate seamlessly and provide with a mouse click functionality that takes months to develop. Each control boasts various samples and tutorials, extensive documentation and numerous customization options that make it suitable for every type of software and scenario.

Further details about each component in the pack are available from MindFusion website:

Use this link to buy a license online. All components are royalty-free.

MindFusion Chart Control for WinForms, V4.0 Beta

MindFusion is proud to present you the beta version of Charting for WinForms, V4.0. MindFusion has entirely redesigned the control to create the most agile, lean and smart charting tool on the market. Below is a brief synopsis of the new chart for WinForms component.

New data model
Data that should be drawn in charts is read through an interface called Series, whose instances can be assigned to the Series properties of Chart and SeriesRenderer classes. You could implement this interface in your own model classes to avoid duplicating data. The library includes several pre-defined series classes that let you specify data via IList or array objects. For example, BarSeries lets you specify lists of values, inner labels and top labels, and PointSeries lets you specify data as a list of points.

Radar chart with multiple series.

Radar chart with multiple series.

New rendering model
Chart graphics are drawn inside Plot components by SeriesRenderer -derived objects. Each plot can contain multiple series renderers from same or different types. For example, you can draw area, line and bar graphics in same plot by adding AreaRenderer, LineRenderer and BarRenderer objects to its SeriesRenderers collection. Concrete Chart classes automatically generate a series renderer of appropriate type for their Series.

Dashboard
The Dashboard control can contain multiple plots, axes, legends, images, gauges and text blocks arranged in dynamic layout. Individual components can be added to dashboard’s default RootPanel or LayoutPanel containers, or for more complex layouts add intermediary panels such as GridPanel and StackPanel to the default ones.

The new WinForms Chart  has a built-in dashboard control.

The new WinForms Chart has a built-in dashboard control.

Print and export
The Dashboard control and Chart controls that derive from it expose Print and PrintPreview methods for printing on paper. Call the ExportImage and CreateImage methods to generate bitmap image of the dashboard. The ExportPdf method exports the chart to a PDF (Portable Document Format) file. The ExportSvg method exports the chart to an SVG (Scalable Vector Graphics) file.

Styling
Values of appearance properties can come from several places in the component hierarchy. SeriesRenderer -derived objects can use attributes from their local SeriesStyle, from plot’s SeriesStyle, or from the *Series properties in current Theme. Component classes use either their local properties or ones defined in the theme. By default, appearance properties in SeriesRenderer and Component classes have null values, which makes the drawing code use values from the theme.

You can download the beta version directly from the link below. The archive file contains the control’s libraries, samples in C# and documentation.

Download Chart for WinForms, V4.0 Beta Version

Your feedback is valuable for us. Please use the forum or e-mail support@mindfusion.eu. to share your opinion, ask questions or submit a problem.

About Chart for WinForms: This is a smart WinForms dashboard control that lets you add the perfect chart or gauge to your application in a few easy steps. The control provides an elegant data model, which supports equally well arrays, xml, any .NET data source, lists or any other data model class, that you create by implementing the Series interface.

MindFusion WinForms Chart boasts an innovative rendering model, where each chart graphics is drawn by its own SeriesRenderer on a Plot. Each Plot supports unlimited number of chart or gauge series of any type. Plots, together with axes, legends, gauges, images, and text blocks can be combined in a Dashboard with the built-in dashboard control. Styling the chart is done on various levels – from appearance properties in each SeriesRenderer to more general settings in the Component classes. The control supports themes and comes with a set of stylish themes, which you can customize as you wish or create new ones from scratch.

Persisting the chart is possible in several ways – printing, export to PDF or to Svg images – all of them performed with a single method call.

The newly designed chart control is offered with unchanged prices and license scheme – check it here.

MindFusion.Gauges: Creating a Stopwatch

This blog will demonstrate how to create a simple stopwatch based on the OvalGauge component (part of MindFusion.Charting for WinForms and MindFusion.Pack for WinForms).

Introduction
We start off by creating a new Windows Forms Application in Visual Studio and adding an OvalGauge control to the main form. Set the gauge’s Dock property to Fill and its Name to “stopwatch”.

Setting up the scales
The stopwatch will contain two scales – a bigger one, which should display the seconds, and a smaller one – for the minutes. The minute scale will be positioned in the upper half of the gauge area. The scales can be created and configured in design-time – through the property grid – or in code. In the Property grid navigate to the Scales property of the OvalGauge control and click the ‘…’ button or hit F4 to open the OvalScale Collection Editor. In this editor, add two scales by pressing the ‘Add’ button. Edit the following properties of the second scale:

Name = "SecondsScale"
StartAngle = -90
EndAngle = 270
StartWidth = 0
EndWidth = 0
Stroke = Color=Black, Width=0

MinorTickSettings.ShowTicks = True
MinorTickSettings.Count = 4
MinorTickSettings.Stroke = Color=(85, 85, 85), Width=0
MinorTickSettings.TickShape = Line
MinorTickSettings.TickWidth = 5%
MinorTickSettings.TickAlignment = OuterInside

MiddleTickSettings.ShowLabels = False
MiddleTickSettings.Count = 5
MiddleTickSettings.Stroke = Color=(0, 0, 0), Width=0
MiddleTickSettings.TickShape = Line
MiddleTickSettings.TickWidth = 8%
MiddleTickSettings.TickAlignment = OuterInside

MajorTickSettings.Count = 12
MajorTickSettings.FontFamily = "Calibri"
MajorTickSettings.FontSize = 20%
MajorTickSettings.FontStyle = Regular
MajorTickSettings.LabelOffset = 9%
MajorTickSettings.LabelRotation = None
MajorTickSettings.ShowMaxValueTick = Never
MajorTickSettings.Stroke = Color=(0, 0, 0), Width=2
MajorTickSettings.TickShape = Line
MajorTickSettings.TickWidth = 12%
MajorTickSettings.TickAlignment = OuterInside

In addition, add four custom intervals to the MajorTickSettings.CustomIntervals collection, representing the intervals [0-0], [15-15], [30-30], and [45-45] respectively. Set the Fill property of each custom interval to (187, 31, 33). These objects indicate that the labels inside the corresponding intervals will be colored in red.

For simplicity, the properties of the minute scale are omitted. They are similar to those of the second scale, the main difference being that the minute scale is positioned and sized through the ScaleRelativeCenter and ScaleRelativeRadius properties.

Adding pointers

In the OvalScale Collection Editor dialog add a pointer to each of the two scales. To do this, select the scale, navigate to the Pointers property in the grid and press the ‘…’ button or F4. This will open the Pointer Collection Editor dialog. Name the pointer of the minute scale “MinutesPointer” and the one in the second scale – “SecondsPointer”. We will use these names later in code to identify and search for the pointers. Set the width of the two pointers to 30% and 20% respectively. Then close all editors. We will custom draw the pointers so there is no need to specify any more properties.

To draw the pointers, handle the PrepaintPointer event of the OvalGauge class. This event is raised for each pointer in the gauge individually before the pointer is painted by the control. The event can be used to cancel the default pointer drawing by setting the CancelDefaultPainting to true. A simplified version of the event handler that paints the two pointers is listed below.

private void stopwatch_PrepaintPointer(object sender, PrepaintEventArgs e)
{
    e.CancelDefaultPainting = true;

    Brush fill = new SolidBrush(Color.FromArgb(175, 8, 9));

    GraphicsState state = e.Graphics.Save();
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.ScaleTransform(e.Element.RenderSize.Width, e.Element.RenderSize.Height);

    if (e.Element.Name == "SecondsPointer")
    {
         var polygon = new PointF[]
         {
             new PointF(0.1f, 0.35f),
             new PointF(1, 0.45f),
             new PointF(1, 0.55f),
             new PointF(0.1f, 0.65f)
         };
         var ellipse1 = new RectangleF(0, 0, 0.2f, 1f);

        // Draw the pointer itself
        e.Graphics.FillPolygon(fill, polygon);
        e.Graphics.FillEllipse(fill, ellipse1);
    }
    else if (e.Element.Name == "MinutesPointer")
    {
        var polygon = new PointF[]
        {
            new PointF(0.15f, 0.35f),
            new PointF(1, 0.45f),
            new PointF(1, 0.55f),
            new PointF(0.15f, 0.65f)
        };
        var ellipse1 = new RectangleF(0, 0, 0.3f, 1f);

        e.Graphics.FillPolygon(fill, polygon);
        e.Graphics.FillEllipse(fill, ellipse1);
    }

    e.Graphics.Restore(state);
    fill.Dispose();
}

Activating the stopwatch

Now we need means to start, stop, and reset the stopwatch. First, declare two member variables in the form – startTime and elapsedTime, of type DateTime and TimeSpan respectively. The first variable will store the time when the stopwatch was most recently started. The second variable will store the total elapsed time.

Go to the Visual Studio designer, select the form, navigate to the Padding property and change its value to “0, 0, 0, 50”. The gauge will shrink, leaving some space at the bottom. Add two buttons to the form, below the gauge, and set their texts to “Start” and “Reset” respectively. In addition to the buttons, add a Timer component to the form. When the stopwatch is started, we will use this timer to update the pointers. Handle the Click events of the two buttons. The first button will start/stop the stopwatch. The second button will reset the stopwatch. Here is the event handlers of the two buttons:

private void button1_Click(object sender, EventArgs e)
{
    if (timer1.Enabled)
    {
        UpdateTime();
        UpdatePointers();

        timer1.Stop();
        button1.Text = "Start";
    }
    else
    {
        button1.Text = "Stop";
        startTime = DateTime.Now;
        timer1.Start();
    }
}

private void button3_Click(object sender, EventArgs e)
{
   elapsedTime = TimeSpan.Zero;
   UpdatePointers();
}

Depending on the current state of the application, the first button will either start or stop the timer. The second button will set the elapsed time to 0:00, effectively resetting the stopwatch. Both buttons rely on the method UpdatePointers, which adjusts the gauge pointers according to the currently elapsed time. This method uses the GetElementByName method of the gauge to access the pointers by name and update their values:

private void UpdatePointers()
{
    var minutesPointer = (Pointer)stopwatch.GetElementByName("MinutesPointer");
    var secondsPointer = (Pointer)stopwatch.GetElementByName("SecondsPointer");
    minutesPointer.Value = (float)elapsedTime.TotalMinutes;
    secondsPointer.Value = (float)Math.Round((float)(elapsedTime.TotalSeconds % 60), 1);
}

Finally, handle the Tick event of the timer.

private void timer1_Tick(object sender, EventArgs e)
{
    UpdateTime();
    UpdatePointers();
}

The image below illustrates the running stopwatch:

gauge-stopwatch

The source code of the sample is available for download from here:
https://mindfusion.eu/_samples/GaugesStopwatch.zip

The MindFusion.Charting for WinForms component can be downloaded from here:
https://www.mindfusion.eu/ChartWinFormsTrial.zip

About MindFusion.Charting for WinForms: A professional programming component for WinForms, which lets you create remarkable charts and gauges fast and easy. The tool supports all major chart types – line, pie, radar and bar – and numerous variations of them – column, area, bubble, polar, doughnut etc, as well as oval and linear gauges.