Search code examples
c#drawingpie-chart

How can I round off the edges of pie-chart slices?


I've got C# code to draw a pie chart using the conventional code for each slice:

gr.FillPie(brFill, rect, start_angle, sweep_angle);
gr.DrawPie(penOutline, rect, start_angle, sweep_angle);

This works fine: the trouble is it looks very boring. I'd like to get the effect as below; that is, keeping it 2-D but rounding off the edges. enter image description here

I presume I'd need to use a path gradient brush somehow, but none of the examples I've looked at have helped.

Grateful for any help or tips.

Tony Reynolds


Solution

  • I posted this 11 days ago hoping that someone would do my job for me. I now realise I was wrong and am a reformed character.

    I tried drawing shading and highlights using ControlPaint.Dark() & Light() but couldn't get it to look good. Finally I decided that as most pie charts have a limited range of colours I should set up a series of complete discs with colouring and shading and clip sectors out as required.

    A few sample discs are below:

    enter image description here

    I then set up an equivalent of the FillPie method as below.

           private static void FillImagePie(Graphics gr, Bitmap bm, Rectangle rect, 
                            float startAngle, float sweepAngle)
        // Display a pie slice of a background image. 
        {
    
            // Create a clipping Region
            GraphicsPath pathClip = new GraphicsPath();
            pathClip.AddPie(rect, startAngle, sweepAngle);
            Region regionClip = new Region(pathClip);
    
            // Use region to clip image to the pie sector
            gr.Clip = regionClip;
    
            // Draw the image portion
            gr.DrawImage(bm, rect);
    
            // Clean up
            gr.ResetClip();
            regionClip.Dispose();
            pathClip.Dispose();
    
        }
    

    This takes a disc bitmap, bm, sets up a pie-shaped clip region and draws the image.

    I then needed a control routine that can be called from the Paint overload of the form. In the special case of the pie chart only having one category, the whole disc is displayed. Otherwise each sector is taken in turn. I found in practice that the outline looked ragged, so I first flood the sector with a black brush, then call FillImagePie, then draw a black outline. A sample result is here:

    enter image description here

    I'm happy enough with this effect. All comments and tweaks welcome, and if anyone else has a way to jazz up pie charts please share!

    Tony Reynolds