question

JeffreySchwartz-9279 avatar image
0 Votes"
JeffreySchwartz-9279 asked JeffreySchwartz-9279 commented

Changing font size of label programatically

I am using Visual C# with a WinForm project. I have a fixed-sized label to show some information. I want to be able to change the size of the font depending on the size (length) of the information (I'm trying to make sure all the information fits in the label).

The documentation I read says that I have to create a new font each time I want to change the font size with something life:

label1.Font = new Font(fontFamily, size);

I am concerned that since I will be changing the font size dozens of times, and therefore creating a new font many times, that I will be using up resources. Do I need to somehow dispose of the old font? How does one do that?

An alternative solution I am considering is two labels, one with a smaller font size, one with a larger font size, and programatically deciding which one should be visible and which one should be invisible. Is that a reasonable solution?

Thanks in advance for any advice.

Jeff Schwartz

dotnet-csharpwindows-forms
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Before assigning a new value, call the font's Dispose method.

0 Votes 0 ·

1 Answer

SimpleSamples avatar image
0 Votes"
SimpleSamples answered JeffreySchwartz-9279 commented

In your Form class, you can create multiple fonts only once that exist for the life of the application, as in:

 Font SmallFont = new Font("Arial", 8);
 Font MediumFont = new Font("Arial", 10);
 Font LargeFont = new Font("Arial", 12);

Then set the label1.Font to whatever size you need.

For example the following quick test works for me.

 public partial class Form1 : Form
 {
     Font SmallFont = new Font("Arial", 8);
     Font MediumFont = new Font("Arial", 10);
     Font LargeFont = new Font("Arial", 12);

     public Form1()
     {
         InitializeComponent();
     }

     private void button1_Click(object sender, EventArgs e)
     {
         label1.Font = SmallFont;
     }

     private void button2_Click(object sender, EventArgs e)
     {
         label1.Font = MediumFont;
     }

     private void button3_Click(object sender, EventArgs e)
     {
         label1.Font = LargeFont;
     }
 }


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

This is great, thank you. I'm opening and closing the form with this textbox multiple times so I still have some tweaking to do, but this gives me a great understanding.

0 Votes 0 ·