86

I want a Bitmap icon with bold text to draw it on map. I have a snippet to write text on image:

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) doesn't work for me. I would like the text drawn on the Bitmap to be bolded.

Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382
Sampath Kumar
  • 4,433
  • 2
  • 27
  • 42

3 Answers3

207

Use the setTypeface method on your Paint object to set the font to something with the bold style turned on.

paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • setTypeface allows you to set a font. Fonts have styles, like bold, italic, etc. You can look at the constructors for Typeface and see how to create a font with that style. Once you create one and set it via this call, all future draw commands with this paint will use that font. – Gabe Sechan Jul 29 '13 at 14:38
  • 2
    I tried 6 or 7 answers, and this one was the only one that actually worked. – durbnpoisn Aug 30 '15 at 19:44
  • 58
    A shorter version would be: `paint.setTypeface(Typeface.DEFAULT_BOLD)` rather than calling Typeface.create() – k2col Nov 27 '16 at 12:59
15

For Custom Fonts:

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

For Normal Fonts:

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

and then

paint.setTypeface(typeface);
Ahamadullah Saikat
  • 4,437
  • 42
  • 39
3

Kotlin syntax to setup Paint for bold text

paint = Paint(Paint.ANTI_ALIAS_FLAG).also { it.typeface = Typeface.DEFAULT_BOLD }
Codeversed
  • 9,287
  • 3
  • 43
  • 42