1

我正在尝试将字符串转换为位图,最后我找到了解决方案:

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;

}

我的问题是这个解决方案不适用于所有屏幕(因为宽度和高度不正确)并且有点粗糙。

有没有最好的代码来做到这一点?

非常感谢...

4

1 回答 1

1

不是以像素为单位设置大小,而是将它们设置为倾角,然后转换为像素。像这样

    final float density = context.getResources().getDisplayMetrics().density;
    final float textSizeDips = 10f;
    final float textSizePixels = Math.round(textSizeDips * density);

    paint.setTextSize(textSizePixels);

这将解决不同屏幕上不同文本大小的问题。

于 2012-09-26T16:35:07.227 回答