0

I am using below function to get bitmap from Text. I am not able to position the text in center of the bitmap. A single rule for all below cases to be centered.

"I" "W" "WM" "IQ"

Bitmap DevImjBitmapFrmTxtFnc(String TxtSrgPsgVal)
{
    int TxtSyzVal = 100;
    Paint PenPytVaj = new Paint(ANTI_ALIAS_FLAG);
    PenPytVaj.setTextSize(TxtSyzVal);
    PenPytVaj.setColor(Color.BLUE);
    PenPytVaj.setTextAlign(Paint.Align.CENTER);

    float TxtTitYcoVal = -PenPytVaj.ascent(); // ascent() is negative
    int ImjWytVal = (int) (PenPytVaj.measureText(TxtSrgPsgVal) + 0.0f); // round
    int ImjHytVal = (int) (TxtTitYcoVal + PenPytVaj.descent() + 0.0f);
    Bitmap ImjBitmapVaj = Bitmap.createBitmap(ImjWytVal + TxtSyzVal, ImjHytVal + TxtSyzVal, Bitmap.Config.ARGB_8888);

    Canvas ImjCanvasVaj = new Canvas(ImjBitmapVaj);
    ImjCanvasVaj.drawText(TxtSrgPsgVal, 0, TxtTitYcoVal, PenPytVaj);
    return ImjBitmapVaj;
}

Kindly ignore the diff way of naming the functions and variables used.

Sujay U N
  • 3,942
  • 6
  • 39
  • 65

1 Answers1

1

After One full day of struggle I got this Text Center.
With the help of below link
https://stackoverflow.com/a/32081250/5078763

This is to help all whom I wish not to struggle like me.

Bitmap DevImjBmpFrmTxtFnc(String TxtSrgPsgVal)
{
    int TxtSyzVal = 100;
    TextPaint PenPytVaj = new TextPaint(ANTI_ALIAS_FLAG);
    PenPytVaj.setTextSize(TxtSyzVal);
    PenPytVaj.setColor(Color.BLACK);
    PenPytVaj.setTextAlign(Paint.Align.LEFT);

    Rect TxtRctVar = new Rect();
    PenPytVaj.getTextBounds(TxtSrgPsgVal, 0, TxtSrgPsgVal.length(), TxtRctVar);
    Bitmap TxtImjBmpVar = Bitmap.createBitmap(TxtSyzVal * 2, TxtSyzVal * 2, Bitmap.Config.ARGB_8888);

    Canvas ImjCanvasVaj = new Canvas(TxtImjBmpVar);
    float XcoVal = ImjCanvasVaj.getWidth() / 2 - TxtRctVar.width() / 2  - TxtRctVar.left;
    float YcoVal = ImjCanvasVaj.getHeight() / 2 + TxtRctVar.height() / 2  - TxtRctVar.bottom;
    ImjCanvasVaj.drawText(TxtSrgPsgVal, XcoVal, YcoVal, PenPytVaj);
    return TxtImjBmpVar;
}
Community
  • 1
  • 1
Sujay U N
  • 3,942
  • 6
  • 39
  • 65