安卓画布绘制文本从宽度设置字体大小?
2022-08-31 15:32:11
我想使用一定宽度的文字canvas
.drawtext
例如,无论输入文本是什么,文本的宽度都应始终为。400px
如果输入文本较长,它将减小字体大小,如果输入文本较短,它将相应地增加字体大小。
我想使用一定宽度的文字canvas
.drawtext
例如,无论输入文本是什么,文本的宽度都应始终为。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);
}
然后,您需要做的就是(400是问题中的示例宽度)。setTextSizeForWidth(paint, 400, str);
为了获得更高的效率,您可以将静态类成员,以免每次都对其进行实例化。但是,这可能会引入并发问题,并且可能会妨碍代码的清晰度。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()