Reputation: 5590
I'm trying to convert a String to a bitmap and finally I found a solution:
public static Bitmap textToBitmap(Context c, String text, String typeface, int size, int color){
Paint paint = new Paint();
paint.setTextSize(size);
paint.setTextAlign(Paint.Align.LEFT);
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setColor(color);
Typeface tf = Typeface.createFromAsset(c.getAssets(),typeface);
paint.setTypeface(tf);
int width = (int) (paint.measureText(text) + 0.5f); // round
float baseline = (int) (paint.ascent()*(0.80f) + 0.5f);
int height = (int) (paint.descent()*(0.5f) - paint.ascent()*(0.70f) + 0.5f);
Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int y = (int) (baseline*(-1));
Canvas canvas = new Canvas(image);
canvas.drawText(text, 0, y, paint);
return image;
}
My problem is that this solution doesn't work very well for all screens (because width and height are not correct) and is a bit coarse.
Is there a best code to do this?
Many thanks...
Upvotes: 1
Views: 418
Reputation: 22512
Instead of setting sizes in pixels set them in dips and then convert to pixels. Like this
final float density = context.getResources().getDisplayMetrics().density;
final float textSizeDips = 10f;
final float textSizePixels = Math.round(textSizeDips * density);
paint.setTextSize(textSizePixels);
This will fix problem with different text size on different screens.
Upvotes: 1