Draw Random Circles on a Windows Form (C#)

vegaseat 0 Tallied Votes 3K Views Share

Sooner or later a Csharp snippet had to appear. This one builds a form containing a set of buttons. A bitmap drawing area is used to draw a series of circles with random color, radius and center location. Your creation can be saved as a jpeg image file. You can study the simple code and learn from it.

/*
 * Created using SharpDevelop free C# IDE from
 * http://www.icsharpcode.net/opensource/sd/
 * User: vegaseat
 * 
 * Draw a bunch of random circles or lines on a windows form
 * A very merry Windows Application
 */

using System;
using System.Drawing;  // GDI+ stuff
using System.Drawing.Imaging;  // ImageFormat
using System.Windows.Forms;

namespace DrawLineCircle
{
  // Summary description for Form1
  // a window with five buttons
  public class Form1 : System.Windows.Forms.Form
  {
    private System.Windows.Forms.Button btnLine;
    private System.Windows.Forms.Button btnCircle;
    private System.Windows.Forms.Button btnFill;
    private System.Windows.Forms.Button btnSave;
    private System.Windows.Forms.Button btnClear;

    private Bitmap DrawArea;  // make a persistent drawing area

    // Required designer variable
    private System.ComponentModel.Container components = null;

    private Random rnd;
    private Pen myPen;

    public Form1()
    {
      InitializeComponent();
      rnd = new Random((int)DateTime.Now.Ticks); // seeded with ticks
      myPen = new Pen(Color.Red);
    }

    // Clean up any resources being used
    protected override void Dispose(bool disposing)
    {
      if (disposing)
      {
        if (components != null)
        {
          components.Dispose();
        }
      }
      base.Dispose(disposing);
    }

    #region Windows Form Designer generated code
    private void InitializeComponent()
    {
      this.btnCircle = new System.Windows.Forms.Button();
      this.btnSave = new System.Windows.Forms.Button();
      this.btnLine = new System.Windows.Forms.Button();
      this.btnFill = new System.Windows.Forms.Button();
      this.btnClear = new System.Windows.Forms.Button();
      this.SuspendLayout();
      // 
      // btnCircle
      // 
      this.btnCircle.Location = new System.Drawing.Point(136, 296);
      this.btnCircle.Name = "btnCircle";
      this.btnCircle.Size = new System.Drawing.Size(56, 20);
      this.btnCircle.TabIndex = 0;
      this.btnCircle.Text = "Circle";
      this.btnCircle.Click += new System.EventHandler(this.btnCircle_Click);
      // 
      // btnSave
      // 
      this.btnSave.Location = new System.Drawing.Point(328, 296);
      this.btnSave.Name = "btnSave";
      this.btnSave.Size = new System.Drawing.Size(48, 20);
      this.btnSave.TabIndex = 0;
      this.btnSave.Text = "Save";
      this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
      // 
      // btnLine
      // 
      this.btnLine.Location = new System.Drawing.Point(264, 296);
      this.btnLine.Name = "btnLine";
      this.btnLine.Size = new System.Drawing.Size(54, 20);
      this.btnLine.TabIndex = 1;
      this.btnLine.Text = "Line";
      this.btnLine.Click += new System.EventHandler(this.btnLine_Click);
      // 
      // btnFill
      // 
      this.btnFill.Location = new System.Drawing.Point(200, 296);
      this.btnFill.Name = "btnFill";
      this.btnFill.Size = new System.Drawing.Size(56, 20);
      this.btnFill.TabIndex = 2;
      this.btnFill.Text = "FCircle";
      this.btnFill.Click += new System.EventHandler(this.btnFill_Click);
      // 
      // btnClear
      // 
      this.btnClear.Location = new System.Drawing.Point(8, 296);
      this.btnClear.Name = "btnClear";
      this.btnClear.Size = new System.Drawing.Size(56, 20);
      this.btnClear.TabIndex = 3;
      this.btnClear.Text = "Clear";
      this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
      // 
      // Form1
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
      this.ClientSize = new System.Drawing.Size(380, 325);
      this.Controls.Add(this.btnClear);
      this.Controls.Add(this.btnFill);
      this.Controls.Add(this.btnSave);
      this.Controls.Add(this.btnLine);
      this.Controls.Add(this.btnCircle);
      this.Name = "Form1";
      this.Text = "Draw a few circles ...";
      this.Load += new System.EventHandler(this.Form1_Load);
      this.Closed += new System.EventHandler(this.Form1_Closed);
      this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
      this.ResumeLayout(false);

    }
    #endregion

    //
    // This is the main entry point for the application.
    //
    public static void Main()
    {
      Application.Run(new Form1());
    }

    // Line button click event
    private void btnLine_Click(object sender, System.EventArgs e)
    {
      Graphics xGraph;
      int k;

      xGraph = Graphics.FromImage(DrawArea);

      for(k = 1; k < 40; k++)
      {
        myPen.Color = Color.FromArgb(
          (rnd.Next(0,255)),
          (rnd.Next(0,255)),
          (rnd.Next(0,255)));

        xGraph.DrawLine(
          myPen,
          (int) rnd.Next(0, this.Width),
          (int) rnd.Next(0, this.Height),
          (int) rnd.Next(0, this.Width),
          (int) rnd.Next(0, this.Height));
      }
      xGraph.Dispose();
      this.Invalidate();
    }

    // Circle button click event
    private void btnCircle_Click(object sender, System.EventArgs e)
    {
      Graphics xGraph;
      int k;
      int r;     // radius of circle
      int x, y;  // center coordinates of circle

      xGraph = Graphics.FromImage(DrawArea);

      for(k = 1; k < 40; k++)
      {
        // radius for circle, max 1/2 the width of the form
        r = rnd.Next(0, (this.Width / 2));
        x = rnd.Next(0, this.Width);
        y = rnd.Next(0, this.Height);

        myPen.Color = Color.FromArgb(
          (rnd.Next(0,255)),
          (rnd.Next(0,255)),
          (rnd.Next(0,255)));
        // convert centerX, centerY, radius to bounding rectangle
        xGraph.DrawEllipse( myPen, x-r, y-r, r, r );
      }
      xGraph.Dispose();
      this.Invalidate();
    }

    // FCircle (solid circle) button click event
    private void btnFill_Click(object sender, System.EventArgs e)
    {
      Graphics xGraph;
      int k;
      int r;     // radius of circle
      int x, y;  // center coordinates of circle

      xGraph = Graphics.FromImage(DrawArea);

      // Create solid brush.
      SolidBrush Brush = new SolidBrush(Color.Red);
      for(k = 1; k < 40; k++)
      {
        // radius for circle, max 1/2 the width of the form
        r = rnd.Next(0, (this.Width / 2));
        x = rnd.Next(0, this.Width);
        y = rnd.Next(0, this.Height);

        Brush.Color = Color.FromArgb(
          (rnd.Next(0,255)),
          (rnd.Next(0,255)),
          (rnd.Next(0,255)));
        // convert centerX, centerY, radius to bounding rectangle
        xGraph.FillEllipse( Brush, x-r, y-r, r, r );
      }
      xGraph.Dispose();
      this.Invalidate();
    }

    // form load event
    private void Form1_Load(object sender, System.EventArgs e)
    {
      DrawArea = new Bitmap(this.ClientRectangle.Width,
        this.ClientRectangle.Height,
        System.Drawing.Imaging.PixelFormat.Format24bppRgb);
      InitializeDrawArea();
    }

    private void InitializeDrawArea()
    {
      Graphics xGraph;

      xGraph = Graphics.FromImage(DrawArea);
      // clear the drawing area to background color
      xGraph.Clear(Color.LightYellow);
    }

    // free up resources on program exit
    private void Form1_Closed(object sender, System.EventArgs e)
    {
      DrawArea.Dispose();
    }

    // paint event
    private void Form1_Paint(object sender,
      System.Windows.Forms.PaintEventArgs e)
    {
      Graphics xGraph;

      xGraph = e.Graphics;
      xGraph.DrawImage(DrawArea,0,0,DrawArea.Width,DrawArea.Height);
      xGraph.Dispose();
    }

    // save drawing in bitmap DrawArea as a jpeg file
    private void btnSave_Click(object sender, System.EventArgs e)
    {
      ImageFormat format = ImageFormat.Jpeg;
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Filter = "JPEG Files(*.jpg)|*.jpg";

      if (sfd.ShowDialog()  == DialogResult.OK)
      {
        // now save the image in the DrawArea
        DrawArea.Save( sfd.FileName, format );
      }
    }

    // clear the DrawArea
    private void btnClear_Click(object sender, System.EventArgs e)
    {
      Graphics xGraph;

      xGraph = Graphics.FromImage(DrawArea);
      // clear the drawing area to bg color
      xGraph.Clear(Color.LightYellow);
      // free up resource
      xGraph.Dispose();
      // update
      this.Invalidate();
    }
  }
}
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sorry, just figured out that DrawEllipse() and the Ellipse() function from the WinApi are not exactly the same. It's corrected now.

waterfall 0 Newbie Poster

can we connect these randomly drawn circles.

borjelewin 0 Newbie Poster

Hi,

I get an arithmetic overflow on this line:
rnd = new Random((int)DateTime.Now.Ticks);

The application works fine if I do a bypass:
rnd = new Random((int)15);

But why the overflow?

/BL

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.