2015-05-01 22 views
1

我寫了這個代碼加我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]); 
     } 
    } 
} 

Image應延伸到Label大小。我怎樣才能做到這一點?

回答

5

的能力,顯示和操控圖像和文字在一個相當百搭時尚之間Winforms控制被傳播出去。

  • A Label不能伸展它的Image
  • 一個PictureBoxPanel可以,但他們並沒有表現出應有Text
  • 一個Button都可以做,但將永遠是一個Button,不管你怎樣稱呼它..

因此,要獲得一個組合則需要要麼所有者繪製的東西:

  • DrawImage過載來獲得圖像的大小合適,再加入ImageLabel
  • 或者DrawStringTextPanel顯示它旁邊的圖片

你可以結合兩個控件與正確的能力:

您可以創建一個Panel並設置其BackgroundImage添加到您的圖片及其BackgroundImageLayout=Stretch。然後,你可以用它的文本設置爲Panel的控件集合添加Label

// 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; 

設定的邊界,只要你喜歡..

還有一個選項:如果所有Images應該具有相同的大小如果是256x256像素或更少,可以將它們添加到ImageList。這將以非常簡單的方式將它們拉伸到ImageList.ImageSize,並且您可以將它們添加到您的Label ..

0

如果您正在使用的WinForms,你試試下面:

labels[counter].Size = 
    new Size(labels[counter].Image.Width, labels[counter].Image.Height); 
+0

傑克與您的代碼我的標籤大小更改爲圖像大小,但我希望我的圖像大小標籤大小 –

+0

ahh,if你需要用另一種方式,然後在分配標籤之前調整圖像的大小。 – Jack

+0

我該如何調整圖像大小? –