Home Search   What's New Index Books Links Q & A Newsletter Banners   Feedback Tip Jar MSDN Visual Basic Community

Title Draw a pie chart from an array of values This example shows how to draw a pie chart from an array of values in Visual Basic 6. pie chart, pie slice, wedge, circle Graphics, Algorithms

The DrawPieChart subroutine draws the chart. It loops through the values converting them into radians. It then loops through the angles adding each to the previous one. Finally it draws the pie slices, filled with different colors.

```' Draw a pie chart on object obj with the indicated values.
Private Sub DrawPieChart(ByVal obj As Object, values() As _
Single, ByVal cx As Single, ByVal cy As Single, ByVal _
Const PI As Single = 3.14159265
Dim angles() As Single
Dim i As Integer
Dim total As Single
Dim clr As Integer

' Convert the values into angles in radians.
ReDim angles(LBound(values) - 1 To UBound(values))
total = 0
For i = LBound(values) To UBound(values)
total = total + values(i)
Next i
For i = LBound(values) To UBound(values)
angles(i) = 2 * PI * values(i) / total
Next i

' Add a first value that is a tiny positive value.
angles(LBound(values) - 1) = 0.0000001

' Make each angle be the sum of those before it.
For i = LBound(values) To UBound(values)
angles(i) = angles(i) + angles(i - 1)
If angles(i) > 2 * PI Then angles(i) = 2 * PI
Next i

' Draw the pie chart.
clr = 1
obj.FillStyle = vbFSSolid
For i = LBound(angles) To UBound(angles) - 1
obj.FillColor = QBColor(clr)
obj.Circle (cx, cy), radius, vbBlack, -angles(i), _
-angles(i + 1)
clr = clr + 1
If clr > 15 Then clr = 1
Next i
End Sub```