How to draw multiple rectangles using c#

Posted by Nivas on Stack Overflow See other posts from Stack Overflow or by Nivas
Published on 2010-06-01T09:13:03Z Indexed on 2010/06/02 4:43 UTC
Read the original article Hit count: 339

Filed under:

I have drawn and saved the Rectangle on the image i loaded in the picture box. How i like to draw multiple rectangles for that i tried array in the rectangle but it gives error ("Object reference not set to an instance of an object." (Null reference Exception was unhandled).

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (mybitmap == null)
    {
        mybitmap = new Bitmap(sz.Width, sz.Height);
    }
    rect[count] = new Rectangle(e.X, e.Y, 0, 0);
    this.Invalidate();
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (stayToolStripMenuItem.Checked == true)
    {
        switch (e.Button)
        {
            case MouseButtons.Left:
            {
                rect[count] = new Rectangle(rect[count].Left, rect[count].Top, e.X - rect[count].Left, e.Y - rect[count].Top);
                pictureBox1.Invalidate();

count++: break; }
} } }

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (stayToolStripMenuItem.Checked == true)
    {
        button1.Visible = true;
        button2.Visible = true;

        if (mybitmap == null)
        {
            return;
        }

        using (g = Graphics.FromImage(mybitmap))
        {
            using (Pen pen = new Pen(Color.Red, 2))
            {
                //g.Clear(Color.Transparent);
                e.Graphics.DrawRectangle(pen, rect);
                label1.Top = rect[count].Top; label1[count].Left = rect[count].Left; label1.Width = rect[count].Width;
                label1.Height = rect[count].Height;

                if (label1.TextAlign == ContentAlignment.TopLeft)
                {
                    e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect);
                    g.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect);
                    g.DrawRectangle(pen, rect[count]);
                }
            }
        }
    }
}

How can i do this.....

© Stack Overflow or respective owner

Related posts about c#