Introduction
This article explains how to use the SetPixel method to draw some mathematical functions. I created a MathGraph project under C# (2003) to draw the following functions:
- f(X) = x^2
- f(X) = X^3
- f(X) = sin(X)
- f(X) = cos(X)
- f(X) = |X^2- 4|
- f(X) = |sin(X)|
The MathGraph project has one form (frmGraph) with the following Controls:
- ListBox control (lstFunction) to select a function.
- Label control (lblFunctionName) to display function definition.
- PictureBox control (PicView) to display function graph, this control has background image from the file (..\..\images\Axis.jpg).
- Button control (btnDraw) to draw the function graph.
- Button control (btnExit) to close the program.
The Code
-
- private ArrayList PointArray = new ArrayList();
- private int PageWidth;
- private int PageHeight;
- private int xCenter;
- private int yCenter;
- private Bitmap ImageToDraw;
- private double Pi = Math.PI;
-
-
- private void frmGraph_Load(object sender, System.EventArgs e)
- {
-
- PageWidth = PicView.Width;
- xCenter = (int)PageWidth/2;
-
- PageHeight = PicView.Height;
- yCenter = (int)PageHeight/2;
-
-
- lstFunction.Items.Add("Function 1");
- lstFunction.Items.Add("Function 2");
- lstFunction.Items.Add("Function 3");
- lstFunction.Items.Add("Function 4");
- lstFunction.Items.Add("Function 5");
- lstFunction.Items.Add("Function 6");
- lstFunction.SelectedIndex = 0;
- }
-
-
- private void Function1()
- {
- double W = PageWidth/30;
- double H = PageHeight/80;
-
- ImageToDraw = new Bitmap(PageWidth, PageHeight);
-
- for (double X = -6 ; X <= 6; X+=0.01)
- {
- double Y = Math.Pow(X, 2);
-
- double PX = xCenter + W*X;
-
- double PY = yCenter - H*Y;
- ImageToDraw.SetPixel((int)PX, (int)PY, Color.Blue);
- }
- PicView.Image = ImageToDraw;
- }
Summary
In this article we learned how to use the SetPixel methods to draw the curves and you can go to the source file to see the code for drawing the other functions. If you have any idea about this code, please tell me. Thanks for C# Corner team and thanks for all.