2

When I looked solutions:

How to use a custom typeface in a widget

In the above problem, I use a custom font in a Widget; The use of solution:

public Bitmap buildUpdate(String time) 
  {
    Bitmap myBitmap = Bitmap.createBitmap(160, 84, Bitmap.Config.ARGB_4444);
    Canvas myCanvas = new Canvas(myBitmap);
    Paint paint = new Paint();
    Typeface clock = Typeface.createFromAsset(this.getAssets(),"Clockopia.ttf");
    paint.setAntiAlias(true);
    paint.setSubpixelText(true);
    paint.setTypeface(clock);
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.WHITE);
    paint.setTextSize(65);
    paint.setTextAlign(Align.CENTER);
    myCanvas.drawText(time, 80, 60, paint);
    return myBitmap;
  }

Question:How to determine the width and height of the bitmap generated according to the number of characters?

Community
  • 1
  • 1
see2851
  • 627
  • 1
  • 9
  • 13

1 Answers1

1

With this:

Rect rect = new Rect();
paint.getTextBounds(time, 0, time.length(), rect); // time = your text
int w = rect.width(); // width text
int h = rect.height(); // height of text

This will save the bounds of your text in a Rect and then you can measure the Rect.

Ahmad
  • 69,608
  • 17
  • 111
  • 137
  • I need to increase the width and height so that the font can be displayed properly-->int widthOffset = Utils.dip2px(context, 12); int heightOffset = Utils.dip2px(context, 3); Bitmap myBitmap = Bitmap.createBitmap(rect.width(), size, Bitmap.Config.ARGB_4444); – see2851 Mar 19 '13 at 07:08