Custom Painting Example for Blazor

Nevron NOV Chart for Blazor ships with hundreds of examples with full source code, as part of the Nevron Open Vision Suite. All Blazor Chart examples are also available as a stand-alone Visual Studio solution in C#, which you can download from the links below.

Custom Painting Example for Blazor Description

This example demonstrates how to perform custom paining on the chart.


Custom Painting Example

C# Custom Painting Example Code for Nevron Chart for Blazor
Language: C#

using Nevron.Nov;
using Nevron.Nov.Chart;
using Nevron.Nov.Chart.Tools;
using Nevron.Nov.Dom;
using Nevron.Nov.Graphics;
using Nevron.Nov.Layout;
using Nevron.Nov.Numerics;
using Nevron.Nov.UI;
using Nevron.Nov.Windows.Forms;
using System;
using System.Windows.Forms;

namespace NovWinFormsProject
{
	public partial class Form1 : Form
	{
		#region Constructors

		public Form1()
		{
			InitializeComponent();

			// Set form title
			Text = "NOV WinForms - NCustomPaintingExample";

			// Create the NOV example and its controls
			NWidget exampleContent = CreateExampleContent();
			NWidget exampleControls = CreateExampleControls();
			if (exampleControls != null)
			{
				exampleControls.PreferredWidth = 300;
			}

			// Place the example and its controls in a pair box
			NPairBox pairBox = new NPairBox(exampleContent, exampleControls);
			pairBox.FillMode = ENStackFillMode.First;
			pairBox.FitMode = ENStackFitMode.First;
			pairBox.Margins = new NMargins(NDesign.HorizontalSpacing, NDesign.VerticalSpacing);

			// Host the example in the form
			NNovWidgetHost host = new NNovWidgetHost(pairBox);
			host.Dock = DockStyle.Fill;
			Controls.Add(host);
		}

		#endregion

		#region Example

		public NWidget CreateExampleContent()
		{
			NChartViewWithCommandBars chartViewWithCommandBars = new NChartViewWithCommandBars();
			NChartView chartView = chartViewWithCommandBars.View;
			chartView.Surface.CreatePredefinedChart(ENPredefinedChartType.Cartesian);

			// configure title
			chartView.Surface.Titles[0].Text = "Custom Painting";

			// configure chart
			m_Chart = (NCartesianChart)chartView.Surface.Charts[0];

			m_Chart.SetPredefinedCartesianAxes(ENPredefinedCartesianAxis.XYLinear);

			// setup X axis
			NLinearScale scaleX = new NLinearScale();
			scaleX.MajorGridLines = new NScaleGridLines();
			scaleX.MajorGridLines.Stroke.DashStyle = ENDashStyle.Dot;
			m_Chart.Axes[ENCartesianAxis.PrimaryX].Scale = scaleX;

			// setup Y axis
			NLinearScale scaleY = new NLinearScale();
			scaleY.MajorGridLines = new NScaleGridLines();
			scaleY.MajorGridLines.Stroke.DashStyle = ENDashStyle.Dot;

            // add interlaced stripe for Y axis
            NScaleStrip strip = new NScaleStrip(new NColorFill(NColor.Beige), null, true, 0, 0, 1, 1);
            strip.Interlaced = true;
            scaleY.Strips.Add(strip);

            m_Chart.Axes[ENCartesianAxis.PrimaryY].Scale = scaleY;

			// add a point series
			m_Point = new NPointSeries();
			m_Point.Name = "Point Series";
			m_Point.DataLabelStyle = new NDataLabelStyle(false);
			m_Point.Fill = new NColorFill(new NColor(NColor.DarkOrange, 160));
			m_Point.Size = 5;
			m_Point.Shape = ENPointShape3D.Bar;
			m_Point.UseXValues = true;
			m_Chart.Series.Add(m_Point);

			// add some sample data
			NDataPointCollection dataPoints = m_Point.DataPoints;

			Random random = new Random();

			for (int i = 0; i < 100; i++)
			{
				double u1 = random.NextDouble();
				double u2 = random.NextDouble();

				if (u1 == 0)
					u1 += 0.0001;

				if (u2 == 0)
					u2 += 0.0001;

				double z0 = Math.Sqrt(-2 * Math.Log(u1)) * Math.Cos(2 * Math.PI * u2);
				double z1 = Math.Sqrt(-2 * Math.Log(u1)) * Math.Sin(2 * Math.PI * u2);

				dataPoints.Add(new NPointDataPoint(z0, z1));
			}

			m_Chart.Enabled = true;

            m_Chart.MouseMove += OnChartMouseMove;
            m_Chart.PostPaint += OnChartPostPaint;

            chartView.Document.StyleSheets.ApplyTheme(new NChartTheme(ENChartPalette.Bright, ENChartPaletteTarget.Series));

			return chartViewWithCommandBars;
		}
		/// 
		/// Callled after the chart is painted
		/// 
		/// 
        private void OnChartPostPaint(NPaintEventArgs arg)
        {
			int count = m_Point.DataPoints.Count;

			NPoint mousePosition;
			if (!NMouse.TryGetLocalPosition(m_Chart, out mousePosition))
				return;

			// clamp to plot bounds
			NRectangle viewPlotBounds = m_Chart.ViewPlotBounds;

			if (viewPlotBounds.X > mousePosition.X)
			{
				mousePosition.X = viewPlotBounds.X;
			}
			else if (viewPlotBounds.Right < mousePosition.X)
			{
				mousePosition.X = viewPlotBounds.Right;
			}

			if (viewPlotBounds.Y > mousePosition.Y)
			{
				mousePosition.Y = viewPlotBounds.Y;
			}
			else if (viewPlotBounds.Bottom < mousePosition.Y)
			{
				mousePosition.Y = viewPlotBounds.Bottom;
			}

			int pointCount = 3;
			int[] nearestPointsIndices = new int[pointCount];
			double[] nearestDistances = new double[pointCount];
			
            int[] farthestPointsIndices = new int[pointCount];
			double[] farthestDistances = new double[pointCount];

			for (int i = 0; i < pointCount; i++)
			{
                nearestDistances[i] = GetDataPointDistanceFromPoint(mousePosition, i);
                farthestDistances[i] = GetDataPointDistanceFromPoint(mousePosition, i);
            }

			// determine the nearest and farthest points from the current mouse position
			for (int i = 0; i < count; i++)
			{
				double currentDistance = GetDataPointDistanceFromPoint(mousePosition, i);

				for (int j = 0; j < pointCount; j++)
				{
					if (currentDistance < nearestDistances[j])
					{
						nearestDistances[j] = currentDistance;
						nearestPointsIndices[j] = i;
						break;
					}
				}

				for (int j = 0; j < pointCount; j++)
				{
					if (currentDistance > farthestDistances[j])
					{
						farthestDistances[j] = currentDistance;
						farthestPointsIndices[j] = i;
						break;
					}
				}
			}

			// paint the net of nearest / farthest points
			for (int i = 0; i < pointCount; i++)
			{
				arg.PaintVisitor.SetStroke(new NStroke(2, NColor.Red));
				arg.PaintVisitor.PaintLine(mousePosition, GetDataPointPosition(nearestPointsIndices[i]));

				arg.PaintVisitor.SetStroke(new NStroke(2, NColor.Green));
				arg.PaintVisitor.PaintLine(mousePosition, GetDataPointPosition(farthestPointsIndices[i]));
			}
		}
		/// 
		/// Gets the data point position in content area coordinates
		/// 
		/// 
		/// 
		private NPoint GetDataPointPosition(int index)
		{
            double x = m_Point.DataPoints[index].X;
            double y = m_Point.DataPoints[index].Y;

            return m_Chart.TransformLogicalToView2D(new NPoint(x, y), ENCartesianAxis.PrimaryX, ENCartesianAxis.PrimaryY);
        }
		/// 
		/// 
		/// 
		/// 
		/// 
		/// 
        private double GetDataPointDistanceFromPoint(NPoint point, int index)
		{
			double x = m_Point.DataPoints[index].X;
            double y = m_Point.DataPoints[index].Y;

			NPoint dataPointPosition = GetDataPointPosition(index);

			double dx = point.X - dataPointPosition.X;
            double dy = point.Y - dataPointPosition.Y;

			return Math.Sqrt(dx * dx + dy * dy);
        }

		private void OnChartMouseMove(NMouseEventArgs arg)
        {
			m_Chart.InvalidateDisplay();
        }

        public NWidget CreateExampleControls()
		{
			NStackPanel stack = new NStackPanel();
			NUniSizeBoxGroup group = new NUniSizeBoxGroup(stack);
			
			NComboBox orientationComboBox = new NComboBox();
			orientationComboBox.Items.FillFromEnum();
			orientationComboBox.SelectedIndex = (int)m_Chart.Orientation;
			orientationComboBox.SelectedIndexChanged += OnOrientationComboBoxSelectedIndexChanged;
			stack.Add(NPairBox.Create("Orientation:", orientationComboBox));

			NCheckBox invertScaleCheckBox = new NCheckBox("Invert Scale");
			invertScaleCheckBox.CheckedChanged += OnInvertScaleCheckBoxCheckedChanged;
			stack.Add(invertScaleCheckBox);

			return group;
		}
		public string GetExampleDescription()
		{
			return @"

This example demonstrates how to perform custom paining on the chart.

"; } /// /// Gets the relevant documentation links for the example /// /// public (string Name, string Url)[] GetDocumentationUrls() { return new[] { ("Painting", "https://www.nevron.com/docs/openvision/dom-painting.html"), ("Chart Overview", "https://www.nevron.com/docs/openvision/chart-overview.html"), ("Graphics Overview", "https://www.nevron.com/docs/openvision/graphics-overview.html"), ("Graphics Paths", "https://www.nevron.com/docs/openvision/graphics-paths.html"), ("Stroke", "https://www.nevron.com/docs/openvision/graphics-stroke.html"), }; } #endregion #region Implementation #endregion #region Event Handlers void OnInvertScaleCheckBoxCheckedChanged(NValueChangeEventArgs arg) { for (int i = 0; i < m_Chart.Axes.Count; i++) { m_Chart.Axes[i].Scale.Invert = ((NCheckBox)arg.TargetNode).Checked; } } void OnOrientationComboBoxSelectedIndexChanged(NValueChangeEventArgs arg) { m_Chart.Orientation = (ENCartesianChartOrientation)((NComboBox)arg.TargetNode).SelectedIndex; } #endregion #region Fields NPointSeries m_Point; NCartesianChart m_Chart; #endregion #region Static Methods #endregion #region Constants #endregion #region Nested Types #endregion } }

Download a fully functional C# (.cs) Custom Painting Example for Blazor Solution