Java引用外部字体即自定义字体文件

来源:互联网 发布:淘宝开店需要交1000吗 编辑:程序博客网 时间:2024/06/05 17:03

      有时候我们在程序中,会使用到Java字体,但不是所有的字体系统中都会有,我们就可能会使用外部自定义字体,这样在程序迁移部署中就会少些工作,最近在一个项目中使用到了自定义字体文件,理顺了,记之。

package cy.util;import java.awt.Font;import java.awt.FontFormatException;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;public class CyFont {private Font definedFont = null; public Font getDefinedFont(int ft,float fs) {String fontUrl="";switch (ft) {case 1:fontUrl="/opt/hwxk.ttf";//华文行楷break;case 2:fontUrl="/opt/hwkt.ttf";//华文楷体break;default:String fonturllocal="/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc";if(!new File(fonturllocal).exists()){fontUrl="/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc";}else{fontUrl=fonturllocal;}break;}        if (definedFont == null) {              InputStream is = null;              BufferedInputStream bis = null;              try {                  is =new FileInputStream(new File(fontUrl));                bis = new BufferedInputStream(is);                  definedFont = Font.createFont(Font.TRUETYPE_FONT, is);                //设置字体大小,float型               definedFont = definedFont.deriveFont(fs);            } catch (FontFormatException e) {                  e.printStackTrace();              } catch (IOException e) {                  e.printStackTrace();              } finally {                try {                      if (null != bis) {                          bis.close();                      }                      if (null != is) {                          is.close();                      }                  } catch (IOException e) {                      e.printStackTrace();                  }            }          }          return definedFont;      }  public static void main(String[] args) {// TODO Auto-generated method stubCyFont cf=new CyFont();cf.getDefinedFont(1, 50.0);}}


原创粉丝点击