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



我想使用.drawtextcanvas上绘制一定宽度的文本

例如,无论输入的文本是什么,文本的宽度都应该始终为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成为静态类成员,从而避免每次都实例化它。然而,这可能会引入并发问题,并且可能会阻碍代码的清晰度。

试试这个:

/**
 * Retrieve the maximum text size to fit in a given width.
 * @param str (String): Text to check for size.
 * @param maxWidth (float): Maximum allowed width.
 * @return (int): The desired text size.
 */
private int determineMaxTextSize(String str, float maxWidth)
{
    int size = 0;       
    Paint paint = new Paint();
    do {
        paint.setTextSize(++ size);
    } while(paint.measureText(str) < maxWidth);
    return size;
} //End getMaxTextSize()

Michael Scheper的解决方案看起来不错,但对我来说并不奏效,我需要获得在我的视图中可以绘制的最大文本大小,但这种方法取决于你设置的第一个文本大小。每次设置不同的大小,你都会得到不同的结果,不能说这在任何情况下都是正确的答案。

所以我尝试了另一种方法:

private float calculateMaxTextSize(String text, Paint paint, int maxWidth, int maxHeight) {
    if (text == null || paint == null) return 0;
    Rect bound = new Rect();
    float size = 1.0f;
    float step= 1.0f;    
    while (true) {
        paint.getTextBounds(text, 0, text.length(), bound);
        if (bound.width() < maxWidth && bound.height() < maxHeight) {
            size += step;
            paint.setTextSize(size);
        } else {
            return size - step;
        }
    }
}

很简单,我增加文本大小,直到文本矩形边界尺寸足够接近maxWidthmaxHeight,以减少循环重复,只需将step更改为更大的值(精度与速度),也许这不是实现这一点的最佳方法,但它是有效的。

最新更新