views:

736

answers:

1

The code below creates a 24 slice pie chart. How do I:

  1. Add text labels to each slice a la "Wheel of Fortune".
  2. Rotate the pie chart? I want it to spin like "Wheel of Fortune".

    private void DrawPieChart()
    {
        Graphics g = this.CreateGraphics();
        g.Clear(this.BackColor);
        Rectangle rect = new Rectangle(0, 0, 300, 300);
        float angle = 0;
        Random random = new Random();
        int sectors = 24;
        int sweep = 360 / sectors;
    
    
    
     for(int i=0; i<24;i++)
    {
        Color clr = Color.FromArgb(random.Next(0, 255),random.Next(0, 255), random.Next(0, 255));
        g.FillPie(new SolidBrush(clr), rect, angle, sweep);
        angle += sweep;
    }
    g.Dispose();
    
    }
A: 

To add text labels, call g.DrawString.

EDIT: To make the textvertical like your image, rotate the Graphics object to angle + sweep / 2, and draw your text. To make it draw downward, yopu may be able to draw it in a small width and rely on character wrapping; if that doesn't work, draw it character vy chaaracter and use g.MeasureString to figure out where to put the next character.

To rotate the entire chart, call g.RotateTransform with an angle in degrees before drawing it. EDIT: like this:

    private void DrawPieChart()
    {
        Graphics g = this.CreateGraphics();
        g.Clear(this.BackColor);
        Rectangle rect = new Rectangle(0, 0, 300, 300);
        float angle = 0;
        Random random = new Random();
        int sectors = 24;
        int sweep = 360 / sectors;

         g.RotateTransform(90);        //Rotates by 90 degrees
         for(int i=0; i<24;i++)
        {
            Color clr = Color.FromArgb(random.Next(0, 255),random.Next(0, 255), random.Next(0, 255));
            g.FillPie(new SolidBrush(clr), rect, angle, sweep);
            angle += sweep;
        }
        g.Dispose();
    }

TO animate the rotation, make a field for the angle, increment it on a timer, and pass the field to g.RotateTransform.

Also, the correct way to draw things is to handle the control's Paint event, and draw using e.Graphics. Then, when you want to redraw it, call Invalidate. To prevent flickering, call this.SetStyle(ControlStyles.DoubleBuffer, true); in the constructor.

SLaks
g.DrawString(): I knew that much but I'm not sure how to get the text to align with the slices, e.g. http://www.gamezebo.com/files/screenshots/2123/wheel_of_fortune_2_review_col4.JPGAn example of g.RotateTransform() applied to the code above would be useful. I tried g.RotateTransform() already but couldn't get it to work.
Sajee
For rotation, see edit
SLaks
For vertical text, see second edit.
SLaks