android canvas drawText从宽度设置字体大小? [英] android canvas drawText set font size from width?

查看:3502
本文介绍了android canvas drawText从宽度设置字体大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 .drawtext

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

For example, the width of the text should always be 400px no matter what the input text is.

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

If input text is longer it will decrease the font size, if input text is shorter it will increase the font size accordingly.

推荐答案

这是一种更有效的方法:

Here's a much more efficient method:

/**
 * 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是问题中的示例宽度)。

Then, all you need to do is setTextSizeForWidth(paint, 400, str); (400 being the example width in the question).

为了获得更高的效率,你可以制作 Rect 一个静态类成员,每次都不会实例化它。但是,这可能会引入并发问题,并且可能会阻碍代码清晰度。

For even greater efficiency, you can make the Rect a static class member, saving it from being instantiated each time. However, this may introduce concurrency issues, and would arguably hinder code clarity.

这篇关于android canvas drawText从宽度设置字体大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆