【发布时间】:2015-05-15 03:21:54
【问题描述】:
我想在绘制文本之前获取行数。在我的代码中,我得到了计数(当前行号)。但它的工作不正确。在 while 循环中,我一步一步设置一个单词,然后尝试比较画布宽度和我的临时文本宽度来了解行数。
private void draw(Canvas canvas, String text, int size) {
canvas.drawPaint(paint);
tv = new TextView(mContext);
tv.setTextColor(Color.BLACK);
tv.setTextSize(size);
int lineHeight = tv.getLineHeight();
// max lines on the screen
int lines = canvas.getHeight() / lineHeight;
//max_height = lines * tv.getLineHeight();
String screenText = "";
Pattern stuff = Pattern.compile("[\\w']+|[\\s.,!?;:-]");
Matcher matcher = stuff.matcher(text);
List<String> matchList = new ArrayList<String>();
while (matcher.find()) {
matchList.add(matcher.group(0));
}
// String wholeText[] = text.split(" ");
int i = 0;
String word;
paint.setTextSize(size*3);
while (count <= lines-1&&i<=matchList.size()-1) {
word = matchList.get(i++);
//wholeText[i++];
screenText += word;
tempStr += word;
float w = paint.measureText(tempStr, 0, tempStr.length());
if(canvas.getWidth() <= w) {
count++;
tempStr=word;
}
if(count>lines){
break;
}
tv.setText(screenText);
}
// you have to enable setDrawingCacheEnabled, or the getDrawingCache will return null
tv.setDrawingCacheEnabled(true);
tv.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.EXACTLY));
tv.setPadding(10,0,10,0);
//tv.layout(0, 0, tv.getMeasuredWidth(), lines * tv.getLineHeight());
tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
canvas.drawBitmap(tv.getDrawingCache(), 0, 0, paint);
//canvas.drawText(tv.getText().toString(), 0, 0, paint);
// disable drawing cache
tv.setDrawingCacheEnabled(false);
}
【问题讨论】:
-
@samgak 我用过。但我无法在线获得真实数字。如果没有渲染,我如何获得 textview 宽度?
-
您没有将
tv添加到任何父视图中,您实际上想要实现什么? -
@pskink 我想尽可能多地用文本填充屏幕。我想知道我可以在屏幕上设置多少文本(从整个文本中),并且需要知道最后一个单词设置到屏幕上的位置
-
你为什么不用
StaticLayout类?