sherpensglen sherpensglen - 2 months ago 24
C# Question

how can i draw multiple rectangles in a picturebox in c#?

hi i need help with this i wanna draw multiple rectangles with my function myrectangle but it just draw the last one and erase the first one i dont have much practice with graphics so please help this is what i tried

private void MyRectangle(int p1, int p2 )
{
Bitmap myBitmap = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);

using (Graphics g = Graphics.FromImage(myBitmap))
{

g.DrawRectangle(new Pen(Brushes.Black),p1,p2,30,30);
}
this.pictureBox1.Image = myBitmap;


}
private void Form2_Load(object sender, EventArgs e)
{

MyRectangle(120,120);
MyRectangle(180,120);
}

Answer

everytime you call your functon you replace your image

this.pictureBox1.Image = myBitmap;

you either need multiple pictureboxes, or draw multiple rectangles in your image.

for the later, try something like

        private void MyRectangle(Graphics g, int p1, int p2)
        {           
            g.DrawRectangle(new Pen(Brushes.Black), p1, p2, 30, 30);           
        }

        void GraphicFor(PictureBox pictureBox, Action<Graphic> draw)
        {
            Bitmap myBitmap = new Bitmap(pictureBox.Width, pictureBox.Height);

            using (Graphics g = Graphics.FromImage(myBitmap))
            {
                draw(g);
            }
            pictureBox.Image = myBitmap;
        }
        private void Form2_Load(object sender, EventArgs e)
        {
            GraphicFor(this.pictureBox1, g =>
            {
                MyRectangle(g, 120, 120);
                MyRectangle(g, 180, 120);
            });

        }

(Note, I haven't compiled the above)