GDI+字体Font

 字体,对于大部分人来说都不陌生,在文本编辑软件中(如 Word)字体是必不可少的,同样,在GDI+中,绘制字符串也是需要字体的。在介绍字体Font类的使用之前,先引入一些与其有关的类或者枚举:

 

      (1)字体系列 FontFamily:

            GDI+中将具有相同的样式成为字体系列,如我们常见的 “宋体”、“仿宋”  、“微软雅黑”、 “Arial”等。

 

     (2) 字体风格枚举 FontSytle:

            FontStyle 枚举列出了常见的字体风格,其定义如下:

[csharp]  view plain  copy
  1. enum FontStyle  
  2.   
  3. {  
  4.     Regular,        //常规  
  5.      Bold,           //加粗  
  6.      Italic,         //倾斜  
  7.      Underline,      //下划线  
  8.      Strikout        //强调线  
  9. }  

    

      (3)字体的大小单位 GraphicsUnit :

            在GDI+ 中进行字体描述,文本输出时,不可避免的使用到描述宽度或高度的单位(如像素、磅),GraphicsUnit 枚举列出了GDI+中常用的单位,其定义如下:

[csharp]  view plain  copy
  1. enum GraphicsUnit  
  2.   
  3. {  
  4.      Display,       //指定显示设备的度量单位。通常,视频显示使用的单位是像素;打印机使用的单位是 1/100 英寸。   
  5.       Document,      //将文档单位(1/300 英寸)指定为度量单位。  
  6.       Inch,          //将英寸指定为度量单位。   
  7.       Millimeter,    //将毫米指定为度量单位。  
  8.       Pixel,         //将设备像素指定为度量单位。   
  9.       Point,         //将打印机点(1/72 英寸)指定为度量单位。  
  10.       World          //将世界坐标系单位指定为度量单位。  
  11. }  


     构建字体Font对象:

             再来看看Font类的一个构造函数,在结合以上的信息,聪明的你应该知道这个构造函数该如下去写了吧:

[csharp]  view plain  copy
  1. public Font (FontFamily family,float emSize,FontStyle style,GraphicsUnit unit)  

 

下列Demo示范font 的基本使用:

[csharp]  view plain  copy
  1. private void Form1_Paint(object sender, PaintEventArgs e)  
  2.        {  
  3.            Graphics g = e.Graphics;  
  4.            g.Clear(Color.White);  
  5.   
  6.            //消除锯齿  
  7.            g.SmoothingMode = SmoothingMode.AntiAlias;  
  8.   
  9.            FontFamily fontFamily = new FontFamily("宋体");  
  10.            Font myFont1 = new Font(fontFamily,15,FontStyle.Regular,GraphicsUnit.Pixel);  
  11.            g.DrawString("字体系列为宋体,大小为15,字体风格为常规的黑色字体",myFont1,Brushes.Black,new PointF(10,50));  
  12.   
  13.            Font myFont2 = new Font("Arial",25.5f,FontStyle.Italic,GraphicsUnit.Pixel);  
  14.            g.DrawString("字体系列为Arial,大小为25.5,字体风格为倾斜的红色字体", myFont2, Brushes.Red, new PointF(10, 100));  
  15.   
  16.            Font myFont3 = new Font("微软雅黑", 20, FontStyle.Underline, GraphicsUnit.Pixel);  
  17.            TextRenderer.DrawText(g,"使用TextRenderer类绘制字符串",myFont3,new Point(10,150),Color.Green);  
  18.   
  19.   
  20.            //释放资源  
  21.            fontFamily.Dispose();  
  22.            myFont1.Dispose();  
  23.            myFont2.Dispose();  
  24.            myFont3.Dispose();  
  25.   
  26.        }  



 效果图:

 

 

 

注:如果程序中有大量的文本输出操作,强烈建议使用TextRenderer的DrawText方法而不使用DrawString方法,因为在文本输出方面,DrawText的效率比DrawStrng要高很多。如果有必要,使用抗锯齿模式输出文本。

 

猜你喜欢

转载自blog.csdn.net/wyq429703159/article/details/80234737