Search code examples
c#imagepanelpaintpaintevent

How do I draw an Image into a panel?


I've been trying to fix this issue for hours but whenever I try to draw my image into my panel, it doesn't appear at all. My panel does have a paint event that with the image being "drawn" inside the method. The panel I am trying to draw into does have a background image. I'm not sure if that is interfering with anything. As well as that, the panel is nested in a usercontrol that is nested in a form. One of my questions is, if I do

private void Panel_Paint(object sender, PaintEventArgs e)
{ 
    img = Properties.Resources.Image;
    e.Graphics.DrawImage(img, new Point(0,0));
}

where is it being drawn exactly? to the form? or to the panel?

At first, I tried picture box and I've learned that making the image transparent makes it so that it gets the color of the back color. Confusing part is that I drew that same picture box inside the panel yet it grabbed the color of the form instead. I have not tested out changing the back color of the panel and it probably was just grabbing the same color.


Solution

  • If you have System.Windows.Forms.Panel, then the image will be drawn exactly in the panel starting from the top left corner. No additional configuration required (exact Paint event subscriptions). The image will be drawn at 100% scale, so if the image will be larger than the panel, then you will only see the part of the image.

    So, check the following:

    • img contains the image of the appropriate size
    • there are no transparent parts in the image (to avoid the case where you see only a part of the image and that part is transparent).
    • make sure that the panel itself is visible (add borders?)