首页 > 代码库 > [.NET源码学习]实例化Font,遭遇字体不存在的情况。
[.NET源码学习]实例化Font,遭遇字体不存在的情况。
实例化Font类时,当传入参数为不存在或未安装的字体时,Windows系统会用Microsoft Sans Serif字体替代该字体。
Msdn:
"For more information about how to construct fonts, see How to: Construct Font Families and Fonts. Windows Forms applications support TrueType fonts and have limited support for OpenType fonts. If you attempt to use a font that is not supported, or the font is not installed on the machine that is running the application, the Microsoft Sans Serif font will be substituted."
情景:
利用 New Font("字体",.....) ,当该字体不存在时,我本以为会用系统默认的输入法代替之,后来查看了MSDN,发现事实似乎并非如此。决定查找一下源代码。
源码:
System.Drawing.Font类
1 private void Initialize(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)2 {3 this.originalFontName = familyName;4 this.SetFontFamily(new FontFamily(Font.StripVerticalName(familyName), true));5 this.Initialize(this.fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont);6 }
System.Drawing.FontFamily类
1 internal FontFamily(string name, bool createDefaultOnFail)2 {3 this.createDefaultOnFail = createDefaultOnFail;4 this.CreateFontFamily(name, null);5 }
1 private void CreateFontFamily(string name, FontCollection fontCollection) 2 { 3 IntPtr intPtr = IntPtr.Zero; 4 IntPtr handle = (fontCollection == null) ? IntPtr.Zero : fontCollection.nativeFontCollection; 5 int num = SafeNativeMethods.Gdip.GdipCreateFontFamilyFromName(name, new HandleRef(fontCollection, handle), out intPtr); 6 if (num != 0) 7 { 8 if (this.createDefaultOnFail) 9 {10 intPtr = FontFamily.GetGdipGenericSansSerif();11 }12 else13 {14 if (num == 14)15 {16 throw new ArgumentException(SR.GetString("GdiplusFontFamilyNotFound", new object[]17 {18 name19 }));20 }21 if (num == 16)22 {23 throw new ArgumentException(SR.GetString("GdiplusNotTrueTypeFont", new object[]24 {25 name26 }));27 }28 throw SafeNativeMethods.Gdip.StatusException(num);29 }30 }31 this.SetNativeFamily(intPtr);32 }
1 private static IntPtr GetGdipGenericSansSerif() 2 { 3 IntPtr zero = IntPtr.Zero; 4 int num = SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif(out zero); 5 if (num != 0) 6 { 7 throw SafeNativeMethods.Gdip.StatusException(num); 8 } 9 return zero;10 }
结论:
【SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif】方法,Windows系统下返回Microsoft Sans Serif字体。
由此可见,当实例化字体不存在时,Windows下固定返回Microsoft Sans Serif字体,与系统默认字体无关。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。