简体   繁体   中英

Drawing on PictureBox inside of Panel - C#

The question I have here is sort of a 2 parter.

I have a picturebox that is positioned inside of a panel. When I open an image, the picturebox is resized to the size of the image, while the panel stays the same size. The panel just has scrollbars to see the whole image.

There are 2 things going wrong with this.

  1. When I resize the picturebox, for some reason I can only draw in the previous portion of the picturebox. Ex. The imagebox starts out by default as 200x200. I open an image that is 500x400. And I can only still draw in the 200x200 portion of the image.

  2. The second issue that I am having is that when I do draw in that selective portion of the picturebox, when I scroll to where my painting is out of view, and come back, the image that i painted gone. I know there is some sort of picturebox.invalidate() that I need. I am just not sure how to use it.

Here is my code to get a good grasp on what I'm doing.

public Form1()
    {
        InitializeComponent();

        DrawArea = new Bitmap(pictureBox1.Size.Width, pictureBox1.Size.Height );
        pictureBox1.Image = DrawArea;

        objGraphics = this.pictureBox1.CreateGraphics();
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
            drawImage(e);
    }

    public void drawImage(MouseEventArgs e)
    {
        Rectangle rDraw = new Rectangle();

        if (e.Button == MouseButtons.Left)
        {
            rDraw.X = e.X;
            rDraw.Y = e.Y;
            rDraw.Width = 3;
            rDraw.Height = 3;
            objGraphics.DrawEllipse(System.Drawing.Pens.Black, rDraw);
        }
    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Image Files(*.jpg; *.bmp)|*.jpg; *.bmp";
            if (open.ShowDialog() == DialogResult.OK)
            {
                Bitmap bit = new Bitmap(open.FileName);

                pictureBox1.Size = bit.Size;
                DrawArea = bit;
                pictureBox1.Image = bit;
            }
        }
        catch (Exception)
        {
            throw new ApplicationException("Failed loading image");
        }
    }

Thanks Alot!

You need to draw in the picturebox's Paint event.

You should (almost) never draw on CreateGraphics() .

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