androidcanvasdrawText从宽度设置字体大小?

我想使用.drawtext在特定宽度的canvas上绘制文本

例如,无论input文字是什么,文字的宽度都应该是400px

如果input文字较长,则会减小字体大小,如果input的文字较短,则会相应增加字体大小。

这是一个更有效的方法:

 /** * 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的解决scheme看起来不错,但对我来说并不奏效,我需要获得可以在我的视图中绘制的最大文本大小,但是这种方法取决于您设置的第一个文本大小。每当您设置不同的大小时会得到不同的结果,不能说在任何情况下都是正确的答案。

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

 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 ,减less循环重复只是改变一个更大的值( 准确性与速度 ),也许这不是最好的方式来实现这一点,但有用。