• 使用ttf字体


    有时候我们需要在游戏或应用中使用指定的字体,这些字体在每部手机中不一定要.我们可以将ttf文件添加到应用中,项目的结构图如下:

    图中p5.ttf是我们新增的字体文件.

    以下代码是如何调用与使用字体的.本代码是 [ RB打地鼠 ]的代码片段.


    1. [color=#666666]public void onDraw(Canvas canvas){
    2.   Context context = getContext();
    3.   // 字体
    4.   Typeface typeface = Typeface.createFromAsset(context.getAssets(),"fonts/p5.ttf");
    5.   typefacePaint = new Paint();
    6.   typefacePaint.setTypeface(typeface); // 设置Paint的字体
    7.   typefacePaint.setAntiAlias(true);
    8.   typefacePaint.setTextSize(px2pxByHVGA(context, 18));  // 根据不同分辨率设置字体大小
    9.   canvas.drawText("Score : 10000" ,100,100,typefacePaint); // 画Canvas时,使用设置好字体的Paint
    10. }

    11. public static float px2pxByHVGA(Context context, float pxValue) {
    12.         final float scale = context.getResources().getDisplayMetrics().density;
    13.         return ((pxValue + 0.5f) * scale + 0.5f);
    14. }[/color]
    复制代码

    以上代码中有分辨率的问题 dp与px的转换可以参考我另一篇帖子 [Android中dip(dp)与px之间单位转换]

    以下是效果图:

      还要,该字体文件是经过裁剪的.使用工具是 FontCreator 6.0. 原理就是将ttf字体没有用到的所有中文字全部删除掉,留下有一些用的中文字,英文字和特殊字体.裁剪前的字体文件大小为4MB左右,裁剪后大约只有100KB不到.所以这工作还是非常重要的.

    以下是字体裁剪后的字体文件:

    FontCreator 6.0的使用说明可以百度一下.有些教程讲得相关详细.本人这里就不多说了.

  • 相关阅读:
    【树形dp】Find Metal Mineral
    【树形dp】Apple Tree
    【状压dp】Islands and Bridges
    【状压dp】Travelling
    【状压dp】Most Powerful
    【线段树】Mayor's posters
    【线段树】I Hate It
    【线段树】Atlantis
    【线段树】校门外的树
    【并查集】银河英雄传说
  • 原文地址:https://www.cnblogs.com/wsfjlagr/p/3335059.html
Copyright © 2020-2023  润新知