如何在c#中的图片框中绘制多个矩形?

时间:2016-09-23 04:09:38

标签: c#

嗨,我需要帮助,我想用我的函数myrectangle绘制多个矩形,但它只绘制最后一个并擦除第一个我没有太多的图形练习所以请帮助这是我试过的

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);
     }

1 个答案:

答案 0 :(得分:0)

每当你打电话给你的功能时,你就会替换你的形象

this.pictureBox1.Image = myBitmap;

您需要多个图片框,或在图片中绘制多个矩形。

对于后者,请尝试类似

的内容
        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);
            });

        }

(注意,我还没有编译上面的内容)