简体   繁体   中英

How to keep the image Drawn in PictureBox

Hey everyone, a new guy here in C#.Net.

I'm trying to make an application like Ms Paint, of course much simpler, and I'm stuck.

The problem is this.

In pictureBox, I'm drawing grid lines on the PictureBox, after that I'm reading a .map(A Mapper3 file) and want to draw onto grid lines, but When I draw the map, The grid lines disappers.

I think the problem is because of the PictureBox Image becomes null while I'm drawing the map. How can I overcome this, is there any tricks?

Thanks for the replies from now on, and sorry for my bad English...

My best Regards...

Do you using winforms? If yes, you actually dont need picture box for working area. I think more appropriate would be Graphics class on form or panel. You have lost lines because of form repaint circle, put your drawing code into form paint handler and picture would be repainted when it needed. In some cases you can need to manual trigger repaint circle, for this purposes you should use Invalidate method of your form.

For example, add this code to paint handler:

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        // Drawing vertical lines
        for (int x = 5; x < this.ClientRectangle.Width; x+=5)
        {
            e.Graphics.DrawLine(Pens.Gray, new Point(x, 0), new Point(x, this.ClientRectangle.Height));
        }

        // Drawing horisontal lines
        for (int y = 5; y < this.ClientRectangle.Width; y += 5)
        {
            e.Graphics.DrawLine(Pens.Gray, new Point(0, y), new Point(this.ClientRectangle.Width,y));
        }
    }

You also may use Graphics in button click handler this way:

Graphics g = Graphics.FromHwnd(this.Handle);

g.FillEllipse(Brushes.Beige, new Rectangle(10, 10, 10, 10));

But in this case all you have drawn would be erased during form's repaint circle and you will have to repeint it in form paint handler

[EDIT] Ok, for example you have pictureBox1 on your form, you can easly draw into it with help of Bitmap class in this way:

// Draw into bitmap
Bitmap bmp = new Bitmap(150, 150);
Graphics g = Graphics.FromImage(bmp);
g.FillRectangle(Brushes.Green, new Rectangle(25, 75, 10, 30));

// Set bitmap into picture box
pictureBox1.Image = bmp;

In this case you have no need to redraw your paintings, picture box would do it for you. Dont forget to set BackColor ot picture box to Transparent if you prefer to show paintings from below of picture box.

You have to draw everything including the grid lines whenever the paint event raised, if you are concerned about performance you may detect the clipping area and only draw that portion.

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM