我想将文本绘制到画布上。如何使用自定义字体(例如Helvetica)以及加粗字体?我更愿意使用系统字体而不是从资源中创建。谢谢。
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);
Typeface plain = Typeface.createFromAsset(assetManager, pathToFont); Typeface bold = Typeface.create(plain, Typeface.DEFAULT_BOLD)
。 - Tony the PonygetContext().getAssets()
吗? - WesleyTypeface.DEFAULT_BOLD
也给我带来了问题,但改为 Typeface.BOLD
就可以了。 - CrandellWS如果你正在使用Android的新的Fonts in XML来处理字体,那么为了获取绘制所用的字体,你可以使用以下代码:
val customTypeface = ResourcesCompat.getFont(context, R.font.myfont)
或者如果您的最低Android API版本大于等于26
val customTypeface = resources.getFont(R.font.myfont)
然后将其应用到您的绘画对象:
mTextPaint.typeface = customTypeface
欲了解更多信息,请查看https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml#fonts-in-code
使用这个来进行绘画课:
Paint paint = new Paint();
paint.setTypeface(Typeface.create("Arial",Typeface.ITALIC));
如果您已经使用了某种字体,并想要使用其粗体版本,可以这样做。
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);
我使用了上面的答案,不过对我来说需要做出修改 - 所以想提一下
val textPaint = TextPaint()
textPaint.typeface = resources.getFont(R.font.font_name)
这可能与问题无关,但这正是我在寻找的 - 也许有人也需要它。
ResourcesCompat.getFont(context, R.font.font_name)
。 - Slav自定义字体必须放置在资产文件夹中。
以下代码可能会对您有所帮助
Paint p = new Paint();
//Set font
Typeface plain = Typeface.createFromAsset(context.getAssets(), "custom_font.ttf");
p.setTypeface(plain);
object FontUtils {
private const val FONT_PATH_LATO_REGULAR = "lato_regular.ttf"
fun getDefaultTypeface(context: Context): Typeface {
return Typeface.createFromAsset(context.assets, FONT_PATH_LATO_REGULAR)
}
}
然后您可以将其用作:
paint.typeface = FontUtils.getDefaultTypeface(context)
Canvas
吗? - Tony the Pony