We have a label for example in size 241; 156. And we need the whole text to fit the entire label.

1 answer 1

If you want to reduce the font of the text for this (if the text does not fit):

Float maxSize = 24.0f; label1.Text = "Ваш текст"; label1.Font = new Font(label1.Font.FontFamily, maxSize, label1.Font.Style); while(label1.Width < System.Windows.Forms.TextRenderer.MeasureText(label1.Text, new Font(label1.Font.FontFamily, label1.Font.Size, label1.Font.Style)).Width) { label1.Font = new Font(label1.Font.FontFamily, label1.Font.Size - 0.5f, label1.Font.Style); } 
  • It is advisable to free resources: dispose of the previously created font. Or alternatively, cache the fonts and reuse them. - Alexander Petrov
  • @AlexanderPetrov I apologize, but will not it be cleared when an existing object ceases to refer to it? Do we work with managed resources? - Ivan Kramarchuk pm
  • @AlexanderPetrov I understand that when the handles run out, will the collector work anyway? - Ivan Kramarchuk
  • Garbage collection is non-deterministic and will happen when it is unknown (or maybe never happen at all if there is enough memory). You need to understand that resources are different. For example, handles of the operating system. For each font you need one handle. Meanwhile, the number of handles is limited (in my opinion, ten thousand per process). As a result, handles may not be enough for all the needs of the process. - Alexander Petrov
  • GC monitors memory only. He knows nothing about handles. - Alexander Petrov