如何缩放字符以适合绘制文本的Rect?

时间:2011-10-23 06:25:49

标签: android

我有一个Rects的ArrayList,以及我想要绘制到各个Rects中的字符,每个Rect一个字符。

我想拉伸文本以适应给定的Rect,填充Rect,所以我可以使用canvas.drawText()来绘制文本。

我想我需要setTextSize()和setTextScaleX()的某种组合,但我不知道从哪里开始设置参数。如何让我的角色适合Rects?

希望有人之前已经解决了这个问题,并且可以指出我正确的方向。

1 个答案:

答案 0 :(得分:1)

我最终使用approach使用getTextBounds来确定要使用的文字的大小和比例:

// Adjust text size to fill rect
paint.setTextSize(100);
paint.setTextScaleX(1.0f);
// ask the paint for the bounding rect if it were to draw this text
Rect bounds = new Rect();
paint.getTextBounds(words[i], 0, words[i].length(), bounds);
// get the height that would have been produced
int h = bounds.bottom - bounds.top;
// figure out what textSize setting would create that height of text
float size  = (((float)(rect.height())/h)*100f);
// and set it into the paint
paint.setTextSize(size);
// Now set the scale.
// do calculation with scale of 1.0 (no scale)
paint.setTextScaleX(1.0f);
// ask the paint for the bounding rect if it were to draw this text.
paint.getTextBounds(words[i], 0, words[i].length(), bounds);
// determine the width
int w = bounds.right - bounds.left;
// calculate the baseline to use so that the entire text is visible including the descenders
int text_h = bounds.bottom-bounds.top;
int baseline =bounds.bottom+((rect.height()-text_h)/2);
// determine how much to scale the width to fit the view
float xscale = ((float) (rect.width())) / w;
// set the scale for the text paint
paint.setTextScaleX(xscale);
canvas.drawText(words[i], frame.left + rect.left * scaleX, frame.top + rect.bottom * scaleY - baseline, paint);