java - android canvas drawText从宽度设置字体大小?

标签 java android android-canvas

我想使用 .drawtext

在一定宽度的 canvas 上绘制文本

例如,无论输入文本是什么,文本的宽度都应始终为 400px

如果输入文本较长,则会减小字体大小,如果输入文本较短,则会相应增加字体大小。

最佳答案

这里有一个更有效的方法:

/**
 * Sets the text size for a Paint object so a given string of text will be a
 * given width.
 * 
 * @param paint
 *            the Paint to set the text size for
 * @param desiredWidth
 *            the desired width
 * @param text
 *            the text that should be that width
 */
private static void setTextSizeForWidth(Paint paint, float desiredWidth,
        String text) {

    // Pick a reasonably large value for the test. Larger values produce
    // more accurate results, but may cause problems with hardware
    // acceleration. But there are workarounds for that, too; refer to
    // http://stackoverflow.com/questions/6253528/font-size-too-large-to-fit-in-cache
    final float testTextSize = 48f;

    // Get the bounds of the text, using our testTextSize.
    paint.setTextSize(testTextSize);
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);

    // Calculate the desired size as a proportion of our testTextSize.
    float desiredTextSize = testTextSize * desiredWidth / bounds.width();

    // Set the paint for that size.
    paint.setTextSize(desiredTextSize);
}

然后,您需要做的就是 setTextSizeForWidth(paint, 400, str);(400 是问题中的示例宽度)。

为了提高效率,您可以将 Rect 设为静态类成员,从而避免每次都将其实例化。但是,这可能会引入并发问题,并且可能会妨碍代码的清晰性。

关于java - android canvas drawText从宽度设置字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12166476/

相关文章:

java VTD-解析器逻辑

java - JMustache 中的条件表达式

android - 如何替换 ListView 中的新项目

java - 堆积条形图 : Changing the order of the stacked columns for just one of the bars

android - 自定义 View : onMeasure Height vs Canvas. 高度

java - 发送网络请求而不是等待响应

java - xAxis 条形图中同一位置的所有标签 - JavaFx

android - 在 Android 应用内计费

java - 在Android Kotlin上使用 Canvas mask 输入的文本

android - 我是否需要使用无效调用,如果需要,在哪里?