简体   繁体   中英

How do i insert a Box which i drew out from pen to a picturebox image?

i need help on inserting a box which i drew out from into a picturebox.
here is the code of the pen that i code out, i do not know how to put it in the picturebox. there will be a webcam running on the background of the picturebox, i want my rectangle to be inside the picturebox.

private void button1_Click(object sender, EventArgs e)
{
    if (button1.Text == "Start")
    {
        Graphics myGraphics = base.CreateGraphics();
        myGraphics.Clear(Color.White);
        Pen myPen = new Pen(Color.DarkBlue);
        Rectangle rect = new Rectangle(480, 70, 120, 120);
        myGraphics.DrawRectangle(myPen, rect);
        stopWebcam = false;
        button1.Text = "Stop";
    }
    else
    {
        stopWebcam = true;
        button1.Text = "Start";
    }
}

Paining in winforms is primarily done in the OnPaint event. Your ButtonClick event handler should only setup the stage for OnPaint and possibly activate it. Example:

public class MyForm : Form
    ...
    private Rectangle? _boxRectangle;   

    private void OnMyButtonClick(object sender, EventArgs e)
    {
        if (button1.Text == "Start")
        {
            _boxRectangle = new Rectangle(...);
            button1.Text = "Stop";
        }
        else
        {
            _boxRectangle = null;
            button1.Text = "Start";
        }
        Invalidate(); // repaint
    }

    protected override OnPaint(PaintEventArgs e)
    {
        if (_boxRectangle != null)
        {
            Graphics g = e.Graphics.
            Pen pen = new Pen(Color.DarkBlue);
            g.DrawRectangle(_boxRectangle);
        }
    }
}

You may have to draw the web cam image onto a bitmap buffer and use that as an image for the picture box.

Here is the msdn page with examples at the bottom:

http://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.aspx

Here is my method for doing it.

public void GraphicsToPictureBox (ref PictureBox pb, Graphics graphics,
                              Int32 width, Int32 height) 
{
    Bitmap bitmap = new Bitmap(width,height,graphics);
    pb.Image = bitmap;
}

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