如何在位图上绘制加粗文本?

86

我希望能够在地图上绘制一个带粗体文本的位图图标。我有一个可以将文本写入图像的代码片段:

Bitmap icon = BitmapFactory.decodeResource(PropertyMapList.this.getResources(),
        R.drawable.location_mark);
TextPaint paint = new TextPaint();
paint.setColor(Color.BLACK);
paint.setTextSize(14);
paint.setFakeBoldText(true);
//paint.setTextAlign(Align.CENTER);
Bitmap copy = icon.copy(Bitmap.Config.ARGB_8888, true); 
Canvas canvas = new Canvas(copy);
//canvas.drawText(jsonObj.getString("district_name"), 5, canvas.getHeight()/2, paint);
String districtName = jsonObj.getString("district_name");
StaticLayout layout = new StaticLayout((districtName.length()>25 ? districtName.substring(0, 24)+"..":districtName)+"\n"+jsonObj.getString("total_properties"), paint, canvas.getWidth()-10,Layout.Alignment.ALIGN_CENTER, 1.3f, 0, false);
canvas.translate(5, canvas.getHeight()/2); //position the text
layout.draw(canvas);

setFakeBoldText(true) 对我不起作用,我希望在位图上绘制的文本加粗。

3个回答

209

使用setTypeface方法在您的Paint对象上设置字体,以启用粗体样式。

paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));

setTypeface 允许您设置字体。字体有样式,如粗体、斜体等。您可以查看 Typeface 的构造函数,了解如何创建具有该样式的字体。一旦您创建并通过此调用设置了一个字体,所有未来使用此 paint 的绘制命令都将使用该字体。 - Gabe Sechan
2
我尝试了六七个答案,而这个是唯一一个实际有效的。 - durbnpoisn
58
更简短的写法是:使用 paint.setTypeface(Typeface.DEFAULT_BOLD) 而不是调用 Typeface.create() - k2col

16

对于自定义字体:

Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/bangla/bensen_handwriting.ttf");
Typeface typeface = Typeface.create(font, Typeface.BOLD);

常规字体:

Typeface typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD);
// or
Typeface typeface = Typeface.DEFAULT_BOLD;

然后

paint.setTypeface(typeface);

4

Kotlin设置粗体文本的Paint语法

paint = Paint(Paint.ANTI_ALIAS_FLAG).also { it.typeface = Typeface.DEFAULT_BOLD }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接