Home

GDI+ Circle Animation: One Circle

Introduction

In this example, a filled circle moves back and forth from the top-left to the bottom-right. The shape's size increases when it moves down but decreases when it moves up.

using System;
using System.Drawing;
using System.Windows.Forms;

public enum Inflation { Increase, Decrease }

public class Exercise : Form
{
    private PictureBox pbxCanvas;
    private Timer tmrRefreshCanvas;
    
    public float Radius { get; set; }
    public float CenterX { get; set; }
    public float CenterY { get; set; }
    public Color Color { get; set; }
    public Inflation Direction { get; set; }

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        pbxCanvas = new PictureBox();
        pbxCanvas.Dock = DockStyle.Fill;
        pbxCanvas.BackColor = Color.Black;
        pbxCanvas.Paint += new PaintEventHandler(pbxCanvasPainter);
        Controls.Add(pbxCanvas);

        tmrRefreshCanvas = new Timer();
        tmrRefreshCanvas.Interval = 10;
        tmrRefreshCanvas.Enabled = true;
        tmrRefreshCanvas.Tick += new EventHandler(tmrRefreshCanvasTick);

        Radius = 450.00f;
        CenterX = 225.00f;
        CenterY = 225.00f;
        Color = Color.Yellow;

        Text = "Circular Animation";
        ClientSize = new System.Drawing.Size(900, 900);
        StartPosition = FormStartPosition.CenterScreen;
    }

    public void DrawCircle(Graphics graph)
    {
        graph.FillEllipse(new SolidBrush(Color.Orange), CenterX, CenterY, Radius * 2.00f, Radius * 2.00f);
        graph.DrawEllipse(new Pen(Color.Maroon, 2.00f), CenterX, CenterY, Radius * 2.00f, Radius * 2.00f);
    }

    private void pbxCanvasPainter(object sender, PaintEventArgs e)
    {
        e.Graphics.Clear(Color.Black);
        DrawCircle(e.Graphics);
    }

    private void tmrRefreshCanvasTick(object sender, EventArgs e)
    {
        if (Radius > 500.00f)
            Direction = Inflation.Decrease;

        if (Radius < 50.00f)
            Direction = Inflation.Increase;

        if (Direction == Inflation.Decrease)
        {
            Radius--;
            CenterX = CenterX - 0.50f;
            CenterY = CenterY - 0.50f;
        }
        else
        {
            Radius++;
            CenterX = CenterX + 0.50f;
            CenterY = CenterY + 0.50f;
        }

        pbxCanvas.Invalidate();
    }

    [STAThread]
    public static int Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Exercise());
        return 0;
    }
}

Home Copyright © 2016-2021, FunctionX Home