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:

The Code

  1. ' Variables of my program
  2. Dim PointArray As ArrayList = New ArrayList ' series of points
  3. Dim PageWidth As Integer ' Width of "ImageToDraw" Object
  4. Dim PageHeight As Integer ' Height of "ImageToDraw" Object
  5. Dim xCenter As Integer ' x coordinate of center
  6. Dim yCenter As Integer ' x coordinate of center
  7. Dim ImageToDraw As Bitmap
  8. Dim Pi As Double = Math.PI ' 22/7
  9. //Set the Center coordinates and load ListBox with Functions:
  10. Private Sub frmGraph_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
  11. ' Width of "PicView" control
  12. PicView.Width = 500 'don't change (it is for background image
  13. ' Height of "PicView" control
  14. PicView.Height = 380 'don't change (it is for background image
  15. ' Width of "ImageToDraw" Object as Width of "PicView" control
  16. PageWidth = PicView.Width
  17. xCenter = Int(PageWidth / 2)
  18. ' Height of "ImageToDraw" Object as Height of "PicView" control
  19. PageHeight = PicView.Height
  20. yCenter = Int(PageHeight / 2)
  21. ' Fill ListBox
  22. lstFunction.Items.Add("Function 1")
  23. lstFunction.Items.Add("Function 2")
  24. lstFunction.Items.Add("Function 3")
  25. lstFunction.Items.Add("Function 4")
  26. lstFunction.Items.Add("Function 5")
  27. lstFunction.Items.Add("Function 6")
  28. lstFunction.SelectedIndex = 0
  29. End Sub
  30. // Draw the function: f(X) = |Sine(X)|
  31. Private Sub Function6()
  32. Dim W As Double = PageWidth / 20
  33. Dim H As Double = PageHeight / 4
  34. ImageToDraw = New Bitmap(PageWidth, PageHeight)
  35. ' Draw the function f(X) = |Sine(X)|.
  36. For X As Double = -2 * Pi To 2 * Pi Step 0.01
  37. Dim Z As Double = Math.Sin(X)
  38. Dim Y As Double = Math.Abs(Z)
  39. Dim PX As Double = xCenter + W * X
  40. Dim PY As Double = yCenter - H * Y
  41. ImageToDraw.SetPixel(Int(PX), Int(PY), Color.Blue)
  42. Next
  43. PicView.Image = ImageToDraw
  44. ImageToDraw = Nothing
  45. 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.