Animate exploding 3-dimensional pie slices in C#

[pie slices]

The example Draw 3-dimensional pie slices in C# shows how to highlight one or more 3-D pie slices by “exploding” them.

This example draws even more attention to the exploded pie slices by animating their explosion. The program controls the explosion with the following variables.

// The distance we have exploded so far.
private float ExplodeDistance = 0;

// The maximum distance we will explode.
private float MaxExplodeDistance = 30;

// The change in explode distance per tick.
private float DeltaExplodeDistance = 2;

When you click the Explode button, the following code executes.

// Start exploding.
private void btnExplode_Click(object sender, EventArgs e)
    ExplodeDistance = 0;
    tmrExplode.Enabled = true;

This code simply resets the exploded distance to 0 and enables the tmrExplode Timer. The following code shows the Timer component’s Tick event handler.

// Continue exploding.
private void tmrExplode_Tick(object sender, EventArgs e)

    ExplodeDistance += DeltaExplodeDistance;
    if (ExplodeDistance > MaxExplodeDistance)
        tmrExplode.Enabled = false;

This code forces the form to redraw so the Paint event handler executes. It then updates the explode distance and, if that distance has reached its maximum value, disables the Timer.

The following code shows the Paint event handler.

// Draw.
private void Form1_Paint(object sender, PaintEventArgs e)
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

    PointF offset_3d = new PointF(0, 20);
    RectangleF rect = new RectangleF(40, 30,
        ClientSize.Width - 80 - offset_3d.X,
        ClientSize.Height - 60 - offset_3d.Y);

    // Set explode distances for slices 2 and 7.
    Slices[2].ExplodeDistance = ExplodeDistance;
    Slices[7].ExplodeDistance = ExplodeDistance;

    // Draw the pie slices in sorted order.
    foreach (Slice slice in Slices)
            slice.TopBrush, slice.TopPen, slice.SideBrush,
            offset_3d, slice.ExplodeDistance, rect,
            slice.StartAngle, slice.SweepAngle);

This code simply updates the ExplodeDistance properties of slices 2 and 7 and then draws all of the slices. In a real application you would update the distances for whichever slices you needed to explode. You could also write similar code to reduce the ExplodeDistance values back to zero to push the slices back into the ellipse when you were done showing them off.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in algorithms, animation, graphics, mathematics, multimedia and tagged , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *