android - 创建位图之前计算文本大小

标签 android canvas bitmap

我有一个根据需要创建的位图。 该位图将包含一个 Canvas ,其中包含一些文本。

正如您可以想象的,该位图将具有固定大小取决于要在 Canvas 上写入的字符长度以及以及指定的文本大小。

例如:

我触发这样的方法:

createBitmapText("This is text", 25); 

现在,我如何计算位图的大小?

我尝试过类似的方法:

int width = text.lenght * textSize;

但是,对于小字符串,它似乎有效,但对于长字符串,有一个很大的空白空间。

有什么建议吗?

这是我的代码 ATM:

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);

结果:

enter image description here

如您所见,看起来不错。

但是,第二个例子:

createBlabla("LONGER", 25);

enter image description here

createBlabla("LONGEST TEXT EVAH", 25);

enter image description here

最佳答案

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

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

关于android - 创建位图之前计算文本大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19915785/

相关文章:

银光 Canvas : How does it work?

android - 在闹钟 android 接收器中听到的 Action 是什么

android - 如何在android中的gridview中显示arraylist

javascript - Three.js – 如何在不调整渲染器大小或缩放内容的情况下调整 Canvas 大小?

android - 无法在android中将矢量可绘制对象转换为位图可绘制对象

android - 在android中将 View 另存为图像

c++ - 如何从 CreateDIBitmap() 函数获取错误代码?

android - 在哪里可以找到最近发布的应用程序?

java - 从 Bundle 接收 null Parcelable 对象

linux - 绘制一个永远不会消失的矩形