我想在绘制文本之前获取行数。在我的代码中,我得到了计数(当前行号)。但它的工作不正确。在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);
}
答案 0 :(得分:0)
只需在这里写:
fun getTextViewStaticLayout(tv: TextView, width: Int): StaticLayout {
val textPaint = TextPaint()
textPaint.isAntiAlias = true
textPaint.textSize = tv.textSize
return StaticLayout(tv.text.toString(), textPaint, width, Layout.Alignment.ALIGN_NORMAL,
1F, 0F, true)
}
width-与textView一起使用(screenWidth或其他)
然后,我们可以使用staticLayout在绘制之前获取textView的属性(lineCount,getLineBottom ...)