我写这段代码来添加我的标签
:
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]);
}
}
}
Image
应该拉伸(stretch)到 Label
大小。我该怎么做?
最佳答案
显示和操作图像和文本的能力在 Winforms
控件中以一种相当疯狂的方式分布。
Label
不能拉伸(stretch)它的Image
。- 一个
PictureBox
和一个Panel
可以,但它们不显示它们的Text
- 一个
Button
可以同时做这两个事情,但无论您如何设计它,它始终是一个Button
..
因此,要获得组合,您需要或者自己绘制一些东西:
DrawImage
在重载中获取图像的正确大小,然后将Image
添加到Label
- 或
DrawString
Text
到Panel
上以在图像旁边显示它
或者您可以将两个具有正确能力的控件结合起来:
您可以创建一个 Panel
并将其 BackgroundImage
设置为您的图像及其 BackgroundImageLayout=Stretch
。然后您可以添加您的 Label
并将其 Text 设置为 Panel
的控件集合:
// 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;
根据需要设置边框..
还有一个选项:如果所有图像
应该具有相同的大小,并且如果它是256x256
像素或更小,您可以将它们添加到图像列表
。这将以一种非常简单的方式将它们拉伸(stretch)到 ImageList.ImageSize
,您可以将它们添加到您的 Label
..
关于c# - 标签图像模式拉伸(stretch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29988307/