1

I have the following code to draw text.

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Paint paint = new Paint();
    paint.setTextSize(400);
    paint.setColor(Color.WHITE);
    paint.setAntiAlias(true);
    paint.setTextAlign(Align.LEFT);
    paint.setStyle(Style.FILL);
    String text = "698";
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);

    int textWidth = bounds.width();        
    int textHeight = bounds.height();

    Bitmap originalBitmap = Bitmap.createBitmap(textWidth,
            textHeight, Bitmap.Config.ARGB_8888);
    Canvas singleUseCanvas = new Canvas(originalBitmap); 
    singleUseCanvas.drawColor(Color.BLUE);
    singleUseCanvas.drawText(text, 0, textHeight, paint);
    canvas.drawBitmap(originalBitmap, 0, 0, null);
}

I am getting undesired outcome, which its right and bottom sides are being cropped.

enter image description here

I avoid right side cropping, by using

float textWidth = paint.measureText(text);
Bitmap originalBitmap = Bitmap.createBitmap((int)(textWidth + 0.5),
                textHeight, Bitmap.Config.ARGB_8888);

I am getting the following improvement

enter image description here

Yet. My bottom still being cropped. May I know what is the correct way to obtained rendered text height, which is analogy to rendered text width using paint.measureText?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

1 Answers1

0

I think i would be helpful to have a look at this post: Android Paint: .measureText() vs .getTextBounds() It have a good survey about sizing of rendered text and also text height which is your concern.

Community
  • 1
  • 1
VSB
  • 9,825
  • 16
  • 72
  • 145