[英]Using custom fonts on a Label on Winforms
我的Winform上有一個標簽,我想使用一種名為XCalibur的自定義字體,使其顯得更加時髦。
如果我在標簽上使用自定義字體,然后構建解決方案,然后.ZIP \\ bin \\ Release中的文件,最終用戶會看到我使用的自定義應用程序的標簽,無論他們是否安裝了該字體?
如果不是這樣,那么在Labels.Text上使用自定義字體的正確方法是什么?
通過查看可能的30-50個帖子后,我終於能夠找到一個真正有效的解決方案! 請按順序執行以下步驟:
1.)在您的應用程序資源中包含您的字體文件(在我的情況下,ttf文件)。 為此,請雙擊“ Resources.resx ”文件。
2.)突出顯示“添加資源”選項,然后單擊向下箭頭。 選擇“添加現有文件”選項。 現在,搜索您的字體文件,選擇它,然后單擊“確定”。 保存“Resources.resx”文件。
3.)創建一個函數(比如,InitCustomLabelFont()),並在其中添加以下代碼。
//Create your private font collection object.
PrivateFontCollection pfc = new PrivateFontCollection();
//Select your font from the resources.
//My font here is "Digireu.ttf"
int fontLength = Properties.Resources.Digireu.Length;
// create a buffer to read in to
byte[] fontdata = Properties.Resources.Digireu;
// create an unsafe memory block for the font data
System.IntPtr data = Marshal.AllocCoTaskMem(fontLength);
// copy the bytes to the unsafe memory block
Marshal.Copy(fontdata, 0, data, fontLength);
// pass the font to the font collection
pfc.AddMemoryFont(data, fontLength);
您的自定義字體現已添加到PrivateFontCollection中。
4.)接下來,將字體分配給Label,並在其中添加一些默認文本。
//After that we can create font and assign font to label
label1.Font = new Font(pfc.Families[0], label1.Font.Size);
label1.Text = "My new font";
5.)轉到表單布局並選擇標簽。 右鍵單擊它並選擇“ 屬性 ”。 查找屬性“ UseCompatibleTextRendering ”並將其設置為“ True ”。
6.)如果有必要,您可以在確定它永遠不會再次使用后釋放字體。 調用PrivateFontCollection.Dispose()方法 ,然后您也可以安全地調用Marshal.FreeCoTaskMem(數據)。 很常見的是不打擾並在應用程序的生命周期中加載字體。
7.)運行您的應用程序。 您現在將看到已為給定標簽設置了自定義字體。
干杯!
嵌入字體作為資源(或只是將其包含在bin目錄下),然后使用PrivateFontCollection
加載的字體(見AddFontFile
和AddMemoryFont
功能)。 然后,您通常使用與機器上安裝的字體相同的字體。
PrivateFontCollection類允許應用程序安裝現有字體的私有版本,而無需替換字體的系統版本。 例如,除了系統使用的Arial字體之外,GDI +還可以創建Arial字體的私有版本。 PrivateFontCollection還可用於安裝操作系統中不存在的字體。
我認為解決方案是將所需的字體嵌入到您的應用程序中。
試試這個鏈接:
http://www.emoreau.com/Entries/Articles/2007/10/Embedding-a-font-into-an-application.aspx
添加要使用的字體。
`
PrivateFontCollection modernFont = new PrivateFontCollection();
modernFont.AddFontFile("Font.otf");
label.Font = new Font(modernFont.Families[0], 40);`
我也做了一個方法。
void UseCustomFont(string name, int size, Label label)
{
PrivateFontCollection modernFont = new PrivateFontCollection();
modernFont.AddFontFile(name);
label.Font = new Font(modernFont.Families[0], size);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.