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


69

我想要一个带有粗体文本的位图图标以将其绘制在地图上。我有一个片段可以在图片上写文字:

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)对我不起作用。我希望在位图上绘制的文本以粗体显示。

Answers:


180

使用对象setTypeface上的方法Paint将字体设置为启用了加粗样式的字体。

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

setTypeface允许您设置字体。字体具有样式,例如粗体,斜体等。您可以查看Typeface的构造函数,并了解如何使用该样式创建字体。一旦创建并通过此调用对其进行设置,以后所有带有此画图的绘制命令都将使用该字体。
加贝·塞尚

2
我尝试了6或7个答案,而这是唯一有效的答案。
durbnpoisn

47
一个简短的版本是:paint.setTypeface(Typeface.DEFAULT_BOLD)而不是调用Typeface.create()
k2col '16

7

对于自定义字体:

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

对于普通字体:

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

接着

paint.setTypeface(typeface);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.