Creating an application to draw graphs of mathematical equations has two components to it, namely, parsing the equation and drawing the results.
Parsing an equation is quite a complicated endeavor. However, I found on the internet a very useful C# library that parses equations very well called dotMath by Steve Hebert. You can visit the website for the library at . Rather than write my own library, I used this library to do all the parsing for me.
The fun part – for me anyway – is trying to draw the graph of an expression. I created a Windows Forms control that contains a picture box that fills the entire control. This picture box will contain the graph that we draw.
The actual generation of the image we are going to draw happens using a Bitmap object.
We set up the pens and brushes we need for the axis, graph, grid and background using the configuration settings that the class contains.
If the flag to draw the axes is set, we first draw the x and y axes, and then label it, using the scale we specify. The offset allows us to move the graph so that the centre of the screen does not need to be the position (0,0), which is the default. The LabelIncrement determines how many pixels apart the labels need to be.
If we set the draw grid flag to true, we also draw a grid, which will make it easier to see what value the graph shows.
Drawing the axes and grid works by taking the centre point and working out along each axis to the end of the screen.
Now that we have set everything up, we can draw the graph.
Here is where we use the dotMath class to parse our equation we want to draw.
So given an example equation of something like “x*x + 3 * X + 23″ or “sin(x)”, we iterate through each pixel, and get the value of x at that pixel based on the scale and offset.
We then replace the character “x” in the equation with our value for x, and pass the string to the equation parser, which then calculates the y value.
From this we can, again using the scale and offset, determine the y value of the coordinate we need.
To actually draw the point, we draw a line from the previous pixel to the current pixel which we have calculated.
continue reading…