Drawing With C#

RwCC 0 Tallied Votes 463 Views Share

The following is a simple painting program. It uses Windows Forms and will allow you to draw whatever you want.

You can also include code to change the colour or size of the brush via a right click menu by using code such as this:

MenuItem mi = new MenuItem("Option");
            mi.Click += new EventHandler(mi_Option);
            cm.MenuItems.Add(mi);

            void mi_Option(object sender, EventArgs e)
            {
            // code to change colour, size etc.
            }

There are bugs with this, if you quickly move the mouse around the lines are not solid. This is because the program is basically drawing multiple circles on the form. Still, it's simple and can be improved upon.

Lots of Google help went into this, so credit goes out to the developers better than myself :)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace Drawing
{
    public partial class PaintingForm : Form
    {
        private Graphics m_objGraphics;
        private Point lastPoint = Point.Empty;
        private bool mouseDown = false;
        private Graphics g;
        private Pen p;
        private Bitmap DrawArea;


        public PaintingForm()
        {
            InitializeComponent();
        }

        private void PainingForm_Load(object sender, EventArgs e)
        {
            DrawArea = new Bitmap(this.ClientRectangle.Width,
            this.ClientRectangle.Height,
            System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            
            m_objGraphics = this.CreateGraphics();

        }

        private void PaintingForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            m_objGraphics.Dispose();
        }

        private void PaintingForm_MouseMove(object sender, MouseEventArgs e)
        {
            Rectangle rectEllipse = new Rectangle();
            Graphics objGraphics;

            if (e.Button != MouseButtons.Left) return;

            rectEllipse.X = e.X - 1;
            rectEllipse.Y = e.Y - 1;
            rectEllipse.Width = 2;
            rectEllipse.Height = 2;

            /*
             * The line below will allow you to easily change the colour, and the size
             * of the line you draw.
             */ 
            m_objGraphics.FillEllipse(new SolidBrush(Color.Cyan), e.X, e.Y, 10, 10);   
        
            }
        }
    }
Ali.M.Habib 0 Newbie Poster

If u draw in the form how can u save it please

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.