Ton*_*ony 158
如果"自定义字体"表示您作为资产提供的字体,则以下代码应该有效:
Typeface plain = Typeface.createFromAsset(assetManager, pathToFont);
Typeface bold = Typeface.create(plain, Typeface.DEFAULT_BOLD)
Paint paint = new Paint();
paint.setTypeface(bold);
canvas.drawText("Sample text in bold",0,0,paint);
Run Code Online (Sandbox Code Playgroud)
Pri*_*tam 14
用于绘画类:
Paint paint = new Paint();
paint.setTypeface(Typeface.create("Arial",Typeface.ITALIC));
Run Code Online (Sandbox Code Playgroud)
Seb*_*zer 14
如果您正在使用Android的XML中的XML新字体作为字体,那么要获得用于绘画的字体,可以使用:
val customTypeface = ResourcesCompat.getFont(context, R.font.myfont)
Run Code Online (Sandbox Code Playgroud)
或者您的最小Android API> = 26
val customTypeface = resources.getFont(R.font.myfont)
Run Code Online (Sandbox Code Playgroud)
然后将其应用于您的绘画对象:
mTextPaint.typeface = customTypeface
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml#fonts-in-code
小智 8
如果您已经使用了某个字体并希望使用其粗体版本,则可以执行此操作.
currentPainter = new Paint(Paint.ANTI_ALIAS_FLAG);
currentPainter.setColor(Color.WHITE);
currentPainter.setTextSize(Utils.sp2px(getResources(), 14)); // set font size
Typeface currentTypeFace = currentPainter.getTypeface();
Typeface bold = Typeface.create(currentTypeFace, Typeface.BOLD);
currentPainter.setTypeface(bold);
Run Code Online (Sandbox Code Playgroud)
我使用了上面的答案,但这个修改对我来说是必要的 - 所以我想我会提到它
如果您想使用资源中的字体(Kotlin):
val textPaint = TextPaint()
textPaint.typeface = resources.getFont(R.font.font_name)
Run Code Online (Sandbox Code Playgroud)
这可能与问题无关,但这就是我一直在寻找的东西 - 也许有人也需要它。