0

I am trying to convert text into image using below code :

    public Bitmap textAsBitmap(String text, float textSize) {
     Paint paint = new Paint(ANTI_ALIAS_FLAG);
     paint.setTextSize(textSize);
     paint.setColor(Color.BLACK);
     paint.setStyle(Paint.Style.FILL_AND_STROKE);
     paint.setTextAlign(Paint.Align.CENTER);
     float baseline = -paint.ascent(); // ascent() is negative
     int width = (int) (paint.measureText(text) + 0.5f); // round
      int height = (int) (baseline + paint.descent() + 0.5f);
      Bitmap image = Bitmap.createBitmap(width, height, 
      Bitmap.Config.ARGB_8888);
     Canvas canvas = new Canvas(image);
     canvas.drawText(text, 0, baseline, paint);
    return image;
}

Its convert text into image but problem is show half text.It should show "favorite subject is english"! enter image description here

what i am doing wrong ? or how should i solve this problem

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Usman Saeed
  • 51
  • 1
  • 6

2 Answers2

1

Choose your width & height wisely, Something like I did in my case

public Bitmap textAsBitmap(String text, float textSize) {
    Paint paint = new Paint(ANTI_ALIAS_FLAG);
    paint.setTextSize(textSize);
    paint.setColor(Color.BLACK);
    paint.setTextAlign(Paint.Align.LEFT);
    float baseline = -paint.ascent(); // ascent() is negative
    int width = (int) (paint.measureText(text) + 0.0f); // round
    int height = (int) (baseline + paint.descent() + 0.0f);

    int actualWidth = width;
    if (width > height) 
        height = width;
    else 
        width = height;
    Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(image);
    canvas.drawText(text, width / 2 - actualWidth / 2, baseline, paint);
    return image;
}
buzzingsilently
  • 1,546
  • 3
  • 12
  • 18
1

Problem is with paint.setTextAlign(Paint.Align.CENTER);, this property considers center as (0,0). So your text is actually at center according to (0,0).

Just remove paint.setTextAlign(Paint.Align.CENTER); and your code is working!!

sneharc
  • 493
  • 3
  • 21