What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleDraw pie slices and see which the user clicks
Keywordspie slice, wedge, circle, click
CategoriesAlgorithms, Graphics

Use the Circle method to draw the pie slices (see also Draw pie slices). In the Form's MouseDown event handler, use the Point method to see which color the user clicked. Iterate through the colors used (this program uses QBColor) to see which region has that color.

Private Sub Form_Load()
Dim angles As Variant
Dim i As Integer
Dim X As Double
Dim Y As Double
Dim R As Double

    AutoRedraw = True
    BackColor = QBColor(15)

    ' Generate 14 angles in degrees (and add
    ' 360 at the end to close the last slice).
    angles = Array(0.0000001, 30, 45, 80, 120, 175, 185, _
        200, 225, 260, 280, 315, 325, 345, 360)

    ' Convert to radians.
    For i = LBound(angles) To UBound(angles)
        angles(i) = angles(i) / 180 * PI
    Next i

    ' Figure out where to put them.
    X = ScaleWidth / 2
    Y = ScaleHeight / 2
    If X > Y Then
        R = Y - 2
        R = X - 2
    End If

    ' Draw the pie slices.
    For i = LBound(angles) To UBound(angles) - 1
        ' Add 1 to skip black.
        FillColor = QBColor(i + 1)
        Circle (X, Y), R, vbBlack, _
            -angles(i), -angles(i + 1)
    Next i
End Sub

' Display a popup menu indicating the region clicked.
Private Sub Form_MouseDown(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
Dim i As Integer
Dim clr As Long

    If (Button And vbRightButton) = 0 Then Exit Sub

    clr = Point(X, Y)
    If clr = BackColor Then Exit Sub

    ' See which region has this color.
    For i = 1 To 14
        If QBColor(i) = clr Then Exit For
    Next i
    If i > 14 Then Exit Sub

    mnuColor.Caption = "Region" & Str$(i)
    PopupMenu mnuPopup
End Sub
For more information on graphics in Visual Basic, see my book Visual Basic Graphics Programming.
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.