Very good community. I use VisualStudio Community 2017, C# language, I want to implement new fonts for a project. Although I thought it was a simple thing to use or add new fonts to the project, after following several tutorials presented on different platforms I still couldn't find what I need.
Although at first I tried to add the fonts to the local fonts of my computer and use them from visual studio, the IDE told me that it only accepts those fonts that are of type TrueType (beyond that I knew that it was a bad practice, because the computer where I am going to install the system does not have that source, nor the need for me to install it). So I started browsing the internet and among several forums I found two tutorials that I followed without success to solve the problem.
- By adding the sources in a folder inside the project and changing its properties so that they are loaded with the build (image 1)
The program crashes before loading and gives me the following error: '(File directory)' is a binary file instead of a text file (image 2)
In one of the tutorials I found this code excerpt:
System.Drawing.Text.PrivateFontCollection privateFonts = new System.Drawing.Text.PrivateFontCollection(); privateFonts.AddFontFile("C:\Documents and Settings\somefont.ttf"); System.Drawing.Font font = new Font(privateFonts.Families[0], 12); label1.Font = font;
When implementing it, I got the following errors about the "privateFonts" attribute: "A field initializer cannot reference the non-static field, method, or property" "does not exist in the current context" (image 3)
To solve these problems, what I did was initialize the font variable inside the windows form constructor, as seen in the following image (image 4)
The problem is when I run the program, at run time the program breaks giving me an error of type "System.IndexOutOfRangeException" and it tells me: "Index outside the limits of the array." on the instance of the font variable (image 5)
Apart from the errors, I am interested in being able to implement the use of new fonts, so any information on this is appreciated.
Greetings.
Everything seems to indicate that you are trying to access the collection
privateFonts.Families
when you have not yet loaded any source file to the object,privateFonts
if it is logical thatprivateFonts.Families
it is empty and therefore the zero index is out of range, I recommend you do the following.