【问题标题】:Which fonts can I use for text in Canvas and How do I get bold style?Canvas 中的文本可以使用哪些字体以及如何获得粗体样式?
【发布时间】:2023-03-03 07:06:23
【问题描述】:

我在画布中使用这样的文本:

paintTextTime.setAntiAlias(true);
paintTextTime.setColor(Color.WHITE);
paintTextTime.setTextSize(60);
canvas.drawText(stringPlayTime, 220, 180, paintTextTime);

我的问题是我如何知道我可以使用哪种字体以及如何将字体样式设置为粗体?

【问题讨论】:

    标签: android


    【解决方案1】:

    您可以通过加载新的TypeFace 轻松更改字体。您可以将任何 TTF 字体放在资产文件夹中并使用以下方法加载它:

    Typeface.createFromAsset(context.getAssets(), "myfont.ttf");
    

    我建议你将加载的字体缓存到prevent memory leaks on older Android versions:

    public class FontCache {
    
        private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();
    
        public static Typeface get(String name, Context context) {
            Typeface tf = fontCache.get(name);
            if(tf == null) {
                try {
                    tf = Typeface.createFromAsset(context.getAssets(), name);
                }
                catch (Exception e) {
                    return null;
                }
                fontCache.put(name, tf);
            }
            return tf;
        }
    }
    

    并像这样使用它:

    Typeface tf = FontCache.get(context, "myfont.ttf");
    Paint paint = new Paint();
    paint.setTypeface(tf);
    canvas.drawText("Lorem ipsum", 0, 0, paint);
    

    【讨论】:

    【解决方案2】:

    谷歌android typefaceThis 是第一个结果,很可能是您要查找的结果。

    【讨论】:

    【解决方案3】:

    您可以使用以下代码

    Typeface tf = Typeface.create("Helvetica",Typeface.BOLD);
    
    Paint paint = new Paint();
    
    paint.setTypeface(tf);
    
    canvas.drawText("Sample text in bold Helvetica",0,0,paint);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 2010-10-11
      • 2021-06-09
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多