I want to get line count before drawing the text. Here in my code I'm getting count(current line number). But it's working not correct. In while loop I'm setting one word at one step then trying to know line count comparing canvas width and my temp text width.
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);
}