Custom Rendering Chart for WinForms C# Tutorial
The Chart Control for Windows Forms supports the custom of data points rendering. It is used to style all data point in the same manner when users plot data in single series. Sometimes, it is also able to customize the appearance of each data point in the series based on the value to provide more information of the plotted data. The following is a tutorial showing the implementation of a kind of series draws a line on a single pass which binds values to predefined colors.
How to Customize Rendering for Line Series
In the following sample, the Line Series will be used to plot the price data for a few categories of fruits in a super market.
- The values of price are defined to the categorical data points and will fall in the range of 0 to 100 dollars.
- The color of the line will change as the below setting when it reaches the certain prices value. a, 10 dollars - gray; b, 30 dollars - blue; c, 50 dollars - yellow; d, 80 dollars - red.
The below tutorial shows the steps:
- Developers need to create a Form in their project and add the Chart control to the Form.
- Create a LineSeries instance and add the categorical data points in the formâs Load event handler. The above sample will generate random values of prices in the range of 0 - 100.
- Add the series to the WinFormsChart.Series collection, set appropriate values to the LabelFormat and LabelFitMode of the HorizontalAxis and VerticalAxis properties.
- Subscribe to the CreateRenderer of the Chart control and instantiate the Renderer property of the event arguments to a new CustomCartesianRederer instance.
- The CreateRenderer event allows users to plug any custom implementation of chart renderer.
- Now create a CustomCartesianRenderer class that inherits CartesianRenderer and overrides the Initialize method.
- After calling the base method, the DrawParts collection contains objects to draw axes, labels, series etc.
- Now we can customize the CustomLineSeriesDrawPart implementation.
- Override the DrawLine method and use the GraphicsPath provided by the GetLinePath method.
- Use a LinearGradientBrush and use its ColorBlend to set appropriate positions and colors to draw a path with gradient colors
- Create a class that will store Color Position couples before getting the CustomLineSeriesDrawPart class
- Go back to the CustomLineSeriesDrawPart, and create a method which calculates the positions and colors that need to be assigned to the ColorBlend of the brush.
- Calculate the color of the points that fall between two predefined values.
- Make sure that the line segments between each two consecutive points are colored properly
- After finishing above steps, developers can get a customized rendering of data points