Android 在创建位图之前计算文本大小

Android 在创建位图之前计算文本大小,android,canvas,bitmap,Android,Canvas,Bitmap,我有一个按需创建的位图。 此位图将包含一个画布,其中包含一些文本 可以想象,此位图将具有固定大小,这取决于要在画布中写入的字符长度,也取决于指定的文本大小 例如: 我触发如下方法: createBitmapText("This is text", 25); 那么现在,我如何计算位图的大小呢 我试过这样的方法: int width = text.lenght * textSize; 然而,对于小字符串,它似乎起作用,但是对于长字符串,有一个很大的空白 有什么建议吗 这是我的代码: publi

我有一个按需创建的位图。 此位图将包含一个画布,其中包含一些文本

可以想象,此位图将具有固定大小,这取决于要在画布中写入的字符长度,也取决于指定的文本大小

例如:

我触发如下方法:

createBitmapText("This is text", 25); 
那么现在,我如何计算位图的大小呢

我试过这样的方法:

int width = text.lenght * textSize;
然而,对于小字符串,它似乎起作用,但是对于长字符串,有一个很大的空白

有什么建议吗

这是我的代码:

public void createBlabla(String text, int fontSize){
    int padding = 15;

    Bitmap largeWhiteBitmap = Bitmap.createBitmap(fontSize * text.length(), fontSize + padding, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(largeWhiteBitmap);

    canvas.drawColor(0xffffffff);

    Paint paint = new Paint();

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
    paint.setTextSize(fontSize);
    paint.setAntiAlias(true);
    canvas.drawText(text, padding, fontSize, paint);


    ImageView imv = (ImageView)MainActivity.this.findViewById(R.id.imageView1);
    imv.setImageBitmap(largeWhiteBitmap);
}
举例说明:

createBlabla("APP", 25);
结果:

正如你所看到的,它看起来不错

Buut,第二个例子:

createBlabla("LONGER", 25);


您可以测量以像素为单位输入的文本的宽度,并相应地设置位图的宽度

Paint paint = new Paint();
paint.setTypeface(Typeface.DEFAULT);
paint.setTextSize(fontSize);
float textWidth = paint.measureText(text)
Paint paint = new Paint();
paint.setTypeface(Typeface.DEFAULT);
paint.setTextSize(fontSize);
float textWidth = paint.measureText(text)