C#使用自定义字体

        /// <summary>
        /// 设置字体
        /// </summary>
        /// <param name="path">字体文件路径,包含字体文件名和后缀名</param>
        /// <param name="fontStyle">字形(常规/粗体/斜体/粗斜体)</param>
        /// <param name="size">大小</param>
        public Font FontSet(string path, FontStyle fontStyle, int size)
        {
            //参数 System.Windows.Forms.Control control,
            //System.Reflection.PropertyInfo per = control.GetType().GetProperty("Font");//判断传进来的控件是否具有Text属性
            //if (per == null)
            //{
            //    return;
            //}
            //String path = System.Windows.Forms.Application.StartupPath + "\\Fonts\\";//font是程序目录下放字体的文件夹
            try
            {
                System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();

                pfc.AddFontFile(path);//字体文件的路径

                Font myFont = new Font(pfc.Families[0], size, fontStyle);
                return myFont;
            }
            catch (System.Exception)
            {
                return null;
                // throw;
            }
        }

 加载系统已安装的字体到列表中:

            //加载系统已经安装的字体
            InstalledFontCollection myFonts = new InstalledFontCollection();
            FontFamily[] fontFamily = myFonts.Families;
            if (fontFamily != null && fontFamily.Length > 0)
            {
                Array.Reverse(fontFamily);
                foreach (FontFamily family in fontFamily)
                {
                    this.lstFontType.Items.Add(family.Name);
                }

            }
            else
            {
                return;
            }

 加载指定路径的字体:

            //加载指定路径下的字体
            string strPat = Application.StartupPath + "\\Fonts\\";
            //遍历指定文件夹中的所有文件
            DirectoryInfo TheFolder = new DirectoryInfo(strPat);

            //遍历文件
            foreach (FileInfo NextFile in TheFolder.GetFiles())
            {

                if (NextFile.Extension.ToLower() == ".ttf")
                {
                    this.lstFontType.Items.Add(NextFile.Name.ToLower().TrimEnd(".ttf".ToCharArray()));
                }
            }

 

posted on 2017-05-18 11:08  印子  阅读(1751)  评论(0编辑  收藏  举报

导航