How do I add an image to a label?

时光总嘲笑我的痴心妄想 提交于 2019-11-28 14:21:50

问题


I have to add image to my label, but I can't find solution how to do this. I'm trying by use this:

        InitializeComponent();
        url = Directory.GetCurrentDirectory() + @"/Cards/cardSkin.png";
        mylabel.Background = new ImageBrush(new BitmapImage(new Uri(url)));

I don't know even if I'm using this right, I just copied this from others project what we did with class. Anyway, I tried to create Image img = Image.FromFile("YourFile.bmp"); but I don't why, .FromFile wasn't working for me. Anyone of you guys have the other way to make label as picture(background) and help newbie do this? :D

Thrown Exception:

Error 1 'System.Windows.Controls.Image' does not contain a definition for 'FromFile.

回答1:


This works for me:

Label ilabel = new Label(); // create a label
Image i = Image.FromFile("image.png"); // read in image
ilabel.Size = new Size(i.Width, i.Height); //set label to correct size
ilabel.Image = i; // put image on label
this.Controls.Add(ilabel); // add label to container (a form, for instance)



回答2:


If you're using a Label created in the Form designer, make sure to set AutoSize to false. Otherwise the .Width will be 0 because the text is empty and modifying the .Size is ignored.

Code like this will work:

label1.Image?.Dispose(); // prevent memory leak
var image = Image.FromFile(@"image.png");
label1.Size = image.Size;
label1.Image = image;



回答3:


Try this

Image img = System.Drawing.Bitmap.FromFile(filename);


来源:https://stackoverflow.com/questions/12848341/how-do-i-add-an-image-to-a-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!