This article shows how to use the SetPixel method to draw some mathematical functions. I created the MathGraph project under VB.NET (2003) to draw the following functions:
1- f(X) = x^2
2- f(X) = X^3
3- f(X) = sin(X)
4- f(X) = cos(X)
5- f(X) = |X^2- 4|
6- 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 the function graph, this control has a 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
-
- Dim PointArray As ArrayList = New ArrayList
- Dim PageWidth As Integer
- Dim PageHeight As Integer
- Dim xCenter As Integer
- Dim yCenter As Integer
- Dim ImageToDraw As Bitmap
- Dim Pi As Double = Math.PI
-
- //Set the Center coordinates and load ListBox with Functions:
- Private Sub frmGraph_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
-
- PicView.Width = 500
-
- PicView.Height = 380
-
-
- 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
- End Sub
-
- // Draw the function: f(X) = |Sine(X)|
- Private Sub Function6()
- Dim W As Double = PageWidth / 20
- Dim H As Double = PageHeight / 4
- ImageToDraw = New Bitmap(PageWidth, PageHeight)
-
- For X As Double = -2 * Pi To 2 * Pi Step 0.01
- Dim Z As Double = Math.Sin(X)
- Dim Y As Double = Math.Abs(Z)
- Dim PX As Double = xCenter + W * X
- Dim PY As Double = yCenter - H * Y
- ImageToDraw.SetPixel(Int(PX), Int(PY), Color.Blue)
- Next
- PicView.Image = ImageToDraw
- ImageToDraw = Nothing
- End Sub
Summary
In this article we have learned how to use the SetPixel method to draw curves. You can go to the source code file to read 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.