Which fonts can I use for text in Canvas and How do I get bold style?
我在画布中使用这样的文本:
1 2 3 4 | paintTextTime.setAntiAlias(true); paintTextTime.setColor(Color.WHITE); paintTextTime.setTextSize(60); canvas.drawText(stringPlayTime, 220, 180, paintTextTime); |
我的问题是如何知道我可以使用哪种字体以及如何将字体样式设置为粗体?
您可以通过加载新的字体来轻松更改字体。您可以将任何 TTF 字体放在资产文件夹中并使用以下命令加载它:
1 | Typeface.createFromAsset(context.getAssets(),"myfont.ttf"); |
我建议您缓存加载的字体以防止旧 Android 版本的内存泄漏:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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; } } |
并像这样使用它:
1 2 3 4 | Typeface tf = FontCache.get(context,"myfont.ttf"); Paint paint = new Paint(); paint.setTypeface(tf); canvas.drawText("Lorem ipsum", 0, 0, paint); |
谷歌
您可以使用以下代码
1 2 3 4 5 6 7 | Typeface tf = Typeface.create("Helvetica",Typeface.BOLD); Paint paint = new Paint(); paint.setTypeface(tf); canvas.drawText("Sample text in bold Helvetica",0,0,paint); |