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

      有时候我们在程序中,会使用到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 stub
		CyFont cf=new CyFont();
		cf.getDefinedFont(1, 50.0);
		
	}

}


  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 18
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值