elnaz irani elnaz irani - 1 month ago 14
C# Question

Label Image mode to stretch

I wrote this code to add my

Labels
:

JArray a = JArray.Parse(temp);
Label[] labels = new Label[100];
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = p.Value.ToString();
if (name == "name")
{
labels[counter] = new Label();
//Image i = Image.FromFile("item.jpg");
labels[counter].Text = value;
labels[counter].Image =Image.FromFile("item.jpg");
//labels[counter].Image
//labels[counter].BackColor = Color.Blue;
labels[counter].TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
labels[counter].Top = height;
height += 50;
Controls.Add(labels[counter]);
}
}
}


The
Image
should stretch to the
Label
Size. How can I do this?

TaW TaW
Answer

The abilities to show and manipulate images and text are spread out in a rather wild fashion among Winforms controls.

  • A Label can not stretch its Image.
  • A PictureBox and a Panel can but they don't show their Text
  • A Button can do both but will always be a Button, no matter how you style it..

So to get a combination you will need to either owner-draw something:

  • DrawImage in an overload to get the right size of the image, then add Image to Label
  • Or DrawString the Text onto a Panel to show it alongside the Image

or you could combine two controls with the right abilities:

You can create a Panel and set its BackgroundImage to your Image and its BackgroundImageLayout=Stretch. Then you can add your Label with its Text set to the Panel's controls collection:

// preparation for testing:
Image image = Image.FromFile("D:\\stop32.png");
Size size = new Size(77, 77);

// create the combined control
// I assume your Label is already there
Panel pan = new Panel();
pan.Size = size;
// or, since the Label has the right size:
pan.Size = label.Size;  // use Clientsize, if borders are involved!
pan.BackgroundImage = image;
pan.BackgroundImageLayout = ImageLayout.Stretch;
label.Parent = pan;  // add the Label to the Panel
label.Location = Point.Empty;
label.Text = "TEXT";
label.BackColor = Color.Transparent;

// add to (e.g.) the form
pan.Parent = this;

Set Borders as you like..

One more option: If all Images should have the same Size and if it is 256x256 pixels or less you could add them to an ImageList. This will stretch them to the ImageList.ImageSize in a very simple way and you can add them to your Label..

Comments