android将自定义字体设置为绘画

Bud*_*ril 86 fonts android paint set

我想画一个文字到油漆.如何用自定义字体(前Helvetica)和粗体绘制它?我宁愿使用系统字体而不是从资产创建它.谢谢.

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)

  • 尝试:`Typeface plain = Typeface.createFromAsset(assetManager,pathToFont); 字体粗体= Typeface.create(plain,Typeface.DEFAULT_BOLD)`. (6认同)
  • @TonythePony您的代码不适合我.字体fontFace = Typeface.createFromAsset(getAssets(),"fonts/comic.TTF"); 字体face = Typeface.create(fontFace,Typeface.BOLD); Paint paint = new Paint(); paint.setTextAlign(Paint.Align.CENTER); paint.setColor(Color.WHITE); paint.setTextSize(10); paint.setTypeface(面部); paint.setFlags(Paint.ANTI_ALIAS_FLAG); (2认同)
  • `Typeface.DEFAULT_BOLD`也给了我一些问题,但是改用`Typeface.BOLD`还是可以的 (2认同)

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)

我使用了上面的答案,但这个修改对我来说是必要的 - 所以我想我会提到它


Paw*_*bin 5

如果您想使用资源中的字体(Kotlin):

val textPaint = TextPaint()
textPaint.typeface = resources.getFont(R.font.font_name)
Run Code Online (Sandbox Code Playgroud)

这可能与问题无关,但这就是我一直在寻找的东西 - 也许有人也需要它。