|
|
Title | Draw a pie chart from an array of values in Visual Basic .NET |
Description | This example shows how to draw a pie chart from an array of values in Visual Basic .NET. |
Keywords | pie chart, pie slice, wedge, circle, VB.NET |
Categories | Graphics, Algorithms |
|
|
The main program geneates some random values and then calls function MakePieChart to make a Bitmap holding the pie chart. It saves the Bitmap in the picChart PictureBox's Image property.
|
|
' Draw pie slices. Note that the DrawPie
' and FillPie methods draw using degrees
' clockwise from horizontal.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
Dim colors() As Color = {Color.Blue, Color.Green, _
Color.Cyan, Color.Red, Color.Magenta, Color.Yellow, _
Color.White, Color.Gray, Color.LightBlue, _
Color.LightGreen, Color.LightCyan, Color.Pink, _
Color.Maroon, Color.LightYellow, Color.SkyBlue}
Dim values(9) As Double
Dim rand As New Random
For i As Integer = 0 To values.Length - 1
values(i) = CSng(20 + rand.NextDouble() * 100)
Next i
picChart.Image = MakePieChart( _
values, colors, _
CInt(picChart.ClientSize.Width * 0.01), _
CInt(picChart.ClientSize.Width * 0.49))
End Sub
|
|
Function MakePieChart adds up all of the values and uses the total to convert the values into parts of 360 degrees. It loops through the angles adding them up so each angle is the sum of the previous angles. Finally it draws the pie slices filled with different colors.
|
|
' Draw a pie chart with the indicated values.
Private Function MakePieChart(ByVal values() As Double, _
ByVal colors() As Color, ByVal margin As Integer, ByVal _
radius As Integer) As Bitmap
' Convert the values into angles in radians.
Dim angles(values.Length) As Single
Dim total As Double = 0
For i As Integer = 0 To values.Length - 1
total = total + values(i)
Next i
For i As Integer = 0 To values.Length - 1
angles(i + 1) = CSng(360 * values(i) / total)
Next i
' Add a first value that is a tiny positive value.
angles(0) = 0.0000001
' Make each angle be the sum of those before it.
For i As Integer = 1 To values.Length
angles(i) = angles(i) + angles(i - 1)
If angles(i) > 360 Then angles(i) = 360
Debug.WriteLine(angles(i)) '@
Next i
' Prepare the Bitmap.
Dim bm As New Bitmap( _
CInt(2 * (margin + radius)), _
CInt(2 * (margin + radius)))
Dim gr As Graphics = Graphics.FromImage(bm)
' Draw the pie chart.
Dim clr As Integer = 0
For i As Integer = 0 To angles.Length - 2
gr.FillPie( _
New SolidBrush(colors(clr)), _
margin, margin, _
2 * radius, 2 * radius, _
angles(i), angles(i + 1) - angles(i))
gr.DrawPie(Pens.Black, margin, margin, _
2 * radius, 2 * radius, _
angles(i), angles(i + 1) - angles(i))
clr = (clr + 1) Mod colors.Length
Next i
gr.Dispose()
Return bm
End Function
|
|
|
|
|
|