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.

Real-time Chart: Amplification Plot

MindFusion.RealTimeCharting for WPF assembly lets you visualize huge (and by that we mean huge) amounts of data with no special load on the machine it runs on. We drew inspiration from a popular chart in molecular biology – Real-time PCR, which:

can provide a simple and elegant method for determining the amount of a target sequence or gene that is present in a sample.

More on the topic here.

Since we self-generate our data, the result graphics are not that much the real thing but they demonstrate the algorithm of building the chart pretty well. Let’s start:

1. Create the chart

Drag the RealTimeChart from the toolbox or add a reference to the MindFusion.RealTimeCharting.Wpf assembly. The chart has no initial data so we start with a simple X-axis on the screen. We name our chart “rtChart”.

2. Customizing the X-axis

The X-axis is accessible via the rtChart.XAxis property. It exposes many appearance settings, from which we start with Interval, Length and Origin – they will define our axis. When data accumulates, the initial axis labels shall be replaced with their updated values.

   rtChart.XAxis.Title = "Cycle";
   rtChart.XAxis.Interval = 2;
   rtChart.XAxis.Length = 50;
   rtChart.XAxis.Origin = 0;
   rtChart.XAxis.LabelFormat = "0";
   rtChart.XAxis.PinLabels = false;

It’s worth noting that we don’t pin labels e.g. they will move along the axis as new data is added. We need no trailing zeros, so the LabelFormat is “0”.

3. The Y-axes

There is no limit on how many Y-axis we will create. In our sample we will use two: one at each side of the chart plot area. We need two instances of the Axis class, which we add to YAxisCollection and Y2AxisCollection respectively. Before we add them, we set their appearance. We want tick marks and rotated title. Note that we align the second axis (Y2) to the right.

   Axis yAxis = new Axis();
   yAxis.Origin = 0.0;
   yAxis.Length = 1;
   yAxis.Interval = 0.1;
   yAxis.Title = "ΔRn";
   yAxis.TitleRotationAngle = -90.0;
   yAxis.TitleFontFamily = new FontFamily("Verdana");
   yAxis.LabelFontFamily = new FontFamily("Verdana");
   yAxis.TickLength = 5;
   yAxis.TitleOffset = 10;
   rtChart.YAxisCollection.Add(yAxis);          

   yAxis = new Axis();
   yAxis.Origin = 0.0;
   yAxis.Length = 100;
   yAxis.Interval = 10;
   yAxis.Title = "Fluorescene";
   yAxis.TitleRotationAngle = -90.0;
   yAxis.TitleFontFamily = new FontFamily("Verdana");
   yAxis.LabelFontFamily = new FontFamily("Verdana");
   yAxis.TickLength = 5;
   yAxis.TitleOffset = 10;
   yAxis.LabelHorizontalAlignment = HorizontalAlignment.Right;
   rtChart.Y2AxisCollection.Add(yAxis);

4. Chart series

We need four series – two of them will be bound to Y and two – to Y2. It’s important to note that axes must be initialized before the series, because each series is associated with a given Y-axis when created.

Each chart series is an instance of the Series class. We want to show scatters at each series – for that we use the ScatterType property. Since we plan to show a legend, it’s important to set the Title of each series – because this title will be used as a legend label. Here is sample code for the first series:

  series1 = new Series(rtChart.YAxisCollection[0])
  {
      Stroke = new SolidColorBrush(Colors.Green),
      ScatterStroke = new SolidColorBrush(Colors.Green),
      Fill = new SolidColorBrush(Colors.Green),
      ScatterType = ScatterType.Diamond,
      Title = "Sample 1",
      TitleFontFamily = new FontFamily("Verdana"),
      TitleFontSize = 12

   };

    .......
   rtChart.SeriesCollection.Add(series1);

5. Data

Data is added directly to the Series.Data property. You can add a batch of points or one point at a time. The property requires that you add a Point e.g. you must set the X and Y values simultaneously:

Point[] points1 = new Point[clusterSize];

//generate some dummy data
...

series1.Data.AddRange(points1);
rtChart.Commit(minNewX);

Don’t forget to call the Commit() method in one of its overloads – it signals to the chart that new data has been added and refresh is needed.

6. Final adjustments

We want a legend and we turn on ShowLegend. The initial result is a legend in 4 rows, which does not look beautifully on our chart. We plat for a while with LegendWidth and LegendHeight and come up with a satisfactory outlook for our legend – in two columns, centered below the plot area.

Adding a tooltip is also easy – we set ShowFallbackTooltip to true. Since the chart might have numerous Y-axis we must choose, which axis the tooltip is bound to. In our case it’s the first one:

    rtChart.TooltipVisibility = Visibility.Visible;
    rtChart.ShowFallbackTooltip = true;
    rtChart.TooltipAxis = rtChart.YAxisCollection[0];

    rtChart.ShowLegend = true;
    rtChart.LegendHeight = 70;

We adjust the grid according to the data we have:

    rtChart.MajorGridSizeY = 50;
    rtChart.MajorGridSizeX = 2;

7. That’s it

Here is the final result:

Real-time chart: amplification plot sample.

Real-time chart: amplification plot sample.

Of course, there are many other settings and possibilities in the control. You can download the sample and expand its functionality and appearance:

Real-time Chart – Amplification Plot Sample Download

MindFusion.RealTimeCharting for WPF is part of MindFusion.Charting for WPF component, which also includes MindFusion.Gauges for WPF. Check the trial version for more practical, beautiful and easy to build charts and gauges.

About MindFusion.RealTimeCharting for WPF: A WPF programming component, which has been designed and developed to render real-time charts with huge amounts of data in a fast and efficient manner. The component uses innovative approach to draw the chart graphics, which forgoes the traditional constructing of a tree with the visual elements in WPF. This way CPU load remains minimal and graphics of tens of thousands of points are rendered with impressive speed. The tool supports unlimited number of Y and Y2 axes, legend, tooltip, background image, grid and more.

About MindFusion.Charting for Wpf: A programming component that combines powerful charting capabilities with an elegant API and easy use. Among the features of the control are fully customizable grid, positive and negative values on all chart axes, 3D charts, gauges and many more – read a detailed list here.

The control provides detailed documentation and various samples that demonstrate how to customize every type of chart. It supports a wide range of 2D and 3D charts including bar, line, radar, bubble pie etc. You can add tooltips, define themes, perform hit testing, zoom and more.

Combine layout algorithms

Apply TreeLayout twice to arrange a genealogy tree

In a series of posts we’ll explore ways to combine graph layout algorithms for various purposes, such as improving layout speed or achieving specific layout constraints.

In this example we’ll show how to apply two TreeLayout instances with different settings to arrange a genealogy tree. The genealogy tree is focused on specific person, with several levels of ancestors drawn above and descendants drawn below. A Visual Studio sample project containing the code from this post is available for download here:

GenealogyLayout.zip

As a start, let’s define a new node class that will draw a person’s photo and name inside a frame, along with their partners’. This will simplify our layout code since we won’t have to take care of keeping partner nodes close to each other:

class GenealogyNode : DiagramNode
{
	public List Partners { get; set; }

	public override void DrawLocal(IGraphics graphics, RenderOptions options)
	{
		float relationLinkLen = Bounds.Width / 7;
		int relations = Partners.Count - 1;
		float personViewWidth = Bounds.Width - relations * relationLinkLen;
		personViewWidth /= Partners.Count;

		var rect = GetLocalBounds();
		rect.Width = personViewWidth;
		for (int i = 0; i < Partners.Count; i++)
		{
			DrawPerson(Partners[i], graphics, rect);

			if (i < Partners.Count - 1)
			{
				float rx = rect.Right;
				float ry = rect.Y + 4 * rect.Height / 5;
				rect.X += personViewWidth + relationLinkLen;
				graphics.DrawLine(Pens.Gray, rx, ry, rect.X, ry);
			}
		}
	}

	public override void DrawShadowLocal(IGraphics graphics, RenderOptions options)
	{
	}

	void DrawPerson(Person person, IGraphics graphics, RectangleF rect)
	{
		const float labelHeight = 5;
		const float padding = 3;

		// draw name
		var labelRect = RectangleF.FromLTRB(
			rect.Left,
			rect.Bottom - labelHeight,
			rect.Right,
			rect.Bottom);

		graphics.DrawString(person.Name,
			EffectiveFont, Brushes.Black, labelRect,
			new StringFormat { Alignment = StringAlignment.Center });

		// draw image
		var imageRect = rect;
		imageRect.Height -= labelHeight + padding;

		Utilities.DrawImage(graphics, person.Image, imageRect, ImageAlign.Fit);

		// draw frame
		var frameColor = person.Gender == Gender.Female ?
			Color.Red : Color.BlueViolet;
		var framePen = new System.Drawing.Pen(frameColor, 0);
		graphics.DrawRectangle(framePen, rect);
		framePen.Dispose();
	}
}

Alternatively, we could draw a single person per node instead, placing partners’ nodes close to each other, grouping them using AttachTo method, and later running TreeLayout with its KeepGroupLayout property enabled.

Now to generate a sample tree, we’ll define recursive methods that will create specified number of ancestor pairs (GenerateAncestors) and create random number of descendants (GenerateDescendants):

void GenerateAncestors(GenealogyNode node, int levels)
{
	if (levels == 0)
		return;
	for (int i = 0; i < 2; i++)
	{
		var p = AddPair();
		var link = diagram.Factory.CreateDiagramLink(p, node);
		link.DestinationAnchor = i;
		link.OriginAnchor = 2;
		GenerateAncestors(p, levels - 1);
	}
}

void GenerateDescendants(GenealogyNode node, int levels)
{
	if (levels == 0)
		return;
	int children = random.Next(1, 5);
	for (int i = 0; i < children; i++)
	{
		int r = random.Next(0, 3);
		if (r == 2)
		{
			var p = AddPair();
			var link = diagram.Factory.CreateDiagramLink(node, p);
			link.OriginAnchor = 2;
			link.DestinationAnchor = 0;
			GenerateDescendants(p, levels - 1);
		}
		else if (r == 1)
		{
			var p = new Person { Name = "daughter", Gender = Gender.Female, Image = fImage };
			var childNode = AddNode(p);
			diagram.Factory.CreateDiagramLink(node, childNode);
		}
		else if (r == 0)
		{
			var p = new Person { Name = "son", Gender = Gender.Male, Image = mImage };
			var childNode = AddNode(p);
			diagram.Factory.CreateDiagramLink(node, childNode);
		}
	}
}

GenealogyNode AddPair()
{
	var p1 = new Person { Name = "mom", Gender = Gender.Female, Image = fImage };
	var p2 = new Person { Name = "dad", Gender = Gender.Male, Image = mImage };
	return AddNode(p1, p2);
}

GenealogyNode AddNode(Person p)
{
	var bounds = new RectangleF(0, 0, 30, 40);

	var node = new GenealogyNode();
	node.Bounds = bounds;
	node.Partners = new List { p };
	node.AnchorPattern = AnchorPattern.TopInBottomOut;
	diagram.Nodes.Add(node);
	return node;
}

GenealogyNode AddNode(Person p1, Person p2)
{
	var bounds = new RectangleF(0, 0, 70, 40);

	var node = new GenealogyNode();
	node.Bounds = bounds;
	node.Partners = new List { p1, p2 };
	node.AnchorPattern = PairPattern;
	diagram.Nodes.Add(node);
	return node;
}

Finally we run TreeLayout twice with specified root node, arranging ancestor nodes above the root and descendant nodes below it, creating the genealogy drawing shown below:

private void GenealogyForm_Load(object sender, EventArgs e)
{
	var root = AddPair();
	GenerateAncestors(root, 2);
	GenerateDescendants(root, 3);

	var l1 = new TreeLayout();
	l1.ReversedLinks = true;
	l1.Direction = TreeLayoutDirections.BottomToTop;
	l1.Anchoring = Anchoring.Keep;
	l1.LevelDistance *= 2;
	l1.NodeDistance *= 1.4f;
	l1.LinkStyle = TreeLayoutLinkType.Cascading3;
	l1.Arrange(diagram);

	var l2 = new TreeLayout();
	l2.Root = root;
	l2.KeepRootPosition = true;
	l2.Anchoring = Anchoring.Keep;
	l2.LevelDistance *= 2;
	l2.NodeDistance *= 1.4f;
	l2.LinkStyle = TreeLayoutLinkType.Cascading3;
	l2.Arrange(diagram);

	diagram.ResizeToFitItems(5);
	//diagramView.ZoomToFit();
}

genealogy tree layout

The code above uses MindFusion’s .NET API and can be used with Windows Forms, WPF, Silverlight and ASP.NET diagramming components. The Java API for Android and desktop Swing application will look similar, with setter method calls instead of property assignments.

You can download the trial version of any MindFusion.Diagramming component from this page.

Enjoy!

Combine layout algorithms

Use OrthogonalLayout to generate initial placement for SpringLayout

In a series of posts we’ll explore ways to combine graph layout algorithms for various purposes, such as improving layout speed or achieving specific layout constraints.

In this example we’ll show how to apply OrthogonalLayout as preprocessing step for SpringLayout used to minimize edge crossings. A problem with force-directed layout algorithms such as SpringLayout is that they can reach equilibrium of the simulated forces while there are link crossings present. However if the simulation starts from an initial layout that has minimal number of crossing, it will tend to reach balance without introducing new crossings. So we can use any of the layout algorithms used for arranging planar graphs (OrthogonalLayout, TriangularLayout, CascadingLayout) to create the initial configuration for SpringLayout.

OrthogonalLayout is designed to create planar drawings of graphs (having no crossing links at all if possible) where edge segments are either horizontal or vertical. For some types of diagrams, such as flowcharts, you might use OrthogonalLayout as is. However in many cases you might prefer SpringLayout, e.g. in order to achieve aesthetic criteria like uniform edge lengths, or to conform to accepted drawing conventions such as the one used to present state machines. So when you know your graphs are planar or close to planar, you can run OrthogonalLayout as pre-processing step, and then run the physical-force simulation using SpringLayout to achieve straight-line uniform length drawings:

void ApplySpringLayout(bool preArrange)
{
    if (preArrange)
    {
        var tl = new OrthogonalLayout();
        tl.Arrange(diagram);
    }

    var sl = new SpringLayout();
    sl.Randomize = false;
    sl.MinimizeCrossings = true;
    sl.IterationCount = 50;
    sl.Arrange(diagram);

    diagramView.ZoomToFit();
}

Here are several examples of the method results when called respectively with false (on the left side) and with true (on the right side of image). Note that for such small graphs SpringLayout will probably remove the crossings if left to run for more iterations, but in the general case and with larger graphs that’s not guaranteed.

1

2

3

The code above uses MindFusion’s .NET API and can be used with Windows Forms, WPF, Silverlight and ASP.NET diagramming components. The Java API for Android and desktop Swing application will look similar, with setter method calls instead of property assignments.

Enjoy!

MindFusion.Spreadsheet: Formatted Text

Starting with version 1.2, MindFusion.Spreadsheet adds support for formatted text. The control can import, create, display and export formatted texts. In this blog we will demonstrate how to create formatted text in a cell.

Introduction

As with all previous blogs we start off by creating a new Windows Forms Application in Visual Studio and adding a WorkbookView control to the main form. The WorkbookView displays a Workbook with a single worksheet.

Creating the formatted text

Formatted texts are created programmatically by instantiating from the FormattedText class. The class provides a constructor, which can initialize the formatted text from a markup string, similar to HTML. The string supports the following tags: <fontname=”fontname“>, <fontsize=”fontsize“>, <i>, <b>, <u>, <s>, and <color=”#rrggbb“>. The following code creates several formatted texts:

worksheet.Cells["A1"].Data = new FormattedText("The meeting is <color=\"#ff0000\">important</color=\"#ff0000\">!");
worksheet.Cells["A2"].Data = new FormattedText("<fontsize=\"18\">A title <fontsize=\"8\">(1994)");
worksheet.Cells["A3"].Data = new FormattedText("This text contains some keywords that are highlighted.");</fontsize=\"8\"></fontsize=\"18\">

Exporting

The formatted texts are exported to all supported formats, including HTML, PDF, XLSX, ODS, image, and so on. The following image illustrated the formatted texts created earlier exported to HTML:

spreadsheet-formattedtext

The source code of the sample is available for download from here:

https://mindfusion.eu/_samples/SpreadsheetFormattedTexts.zip

The trial version of MindFusion.Spreadsheet for WinForms can be downloaded from here:

Download MindFusion.Spreadsheet for WinForms Trial Version

About MindFusion.Spreadsheet for WinForms: A powerful .NET spreadsheet component with great capabilities for editing, styling and formatting large amounts of data.