Sej Sej - 1 month ago 8
C# Question

C# Drawing a Bitmap on a certain point in a PictureBox

I currently have a

Bitmap
image. I need to place this image at a certain coordinate inside a
PictureBox
. Specifically, I'm looking to place it 5 pixels from the top and 5 pixels from the left. The bitmap will be of different lengths, so I want the starting point to always start drawing the
Bitmap
at this specific point.

As an example, here are two "Bitmaps" that both start at the coordinate 5,5, with different lengths. Imagine the Gray is the
PictureBox
:




I've tried something like passing in a
PictureBox
and using graphics to draw the bitmap:

private void setQuantity(PictureBox pb, int quantity) {

Graphics g = pb.CreateGraphics();

g.DrawImage(iqc.createQuantityImage(quantity), 0, 0);

g.Dispose();

}


iqc.createQuantityImage() returns a Bitmap




But this doesn't seem to draw anything. I have also changed the x and y and nothing changes.

I'd like to be able to specify the exact coordinate or point inside the
PictureBox
if possible.

Thanks for any help!

Answer

You can draw image in PictureBox at any location by adding an event handler to its Paint method as follows;

private void PictureBox1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawImage(_myBitmap, new Point(5, 5));    //Here new Point(x,y) determines location in pictureBox where you want to draw the bitmap.
}