support_ms
support_ms

Reputation: 1933

Measuring width of text issue

I'm calculating width of text depending on display's width.I converted display size from pixel(240x320) to dp(320x426).It is clear that measurement of text by Paint class gives results in dp.When I measure three words by given below method it's result is more than 320 , but TextView displays these words at one line also with some little extra space???

private int calcWidthSize(CharSequence cha, int currentSize) {
        TextPaint paint = new TextPaint();
        paint.setTextSize(currentSize);
        return (int) Math.ceil(paint.measureText(cha, 0, cha.length()));
 } 

I tried with another Paint method, but still problem is not solved:

private int calculateWidthSize(CharSequence cha, int currentSize) {
        Rect bounds = new Rect();
        TextPaint paint = new TextPaint();
        paint.setTextSize(currentSize);
        paint.getTextBounds(cha.toString(), 0, cha.length(), bounds);
        return (int) Math.ceil(bounds.width());
 }

Maybe it is TextView's fault? My goal is by measuring text width and height, I should get how much text fits for one page in a textview(display size).Any help please.

Upvotes: 3

Views: 813

Answers (1)

support_ms
support_ms

Reputation: 1933

After some changes on my code I finally got solution:

private float calcWidthSize(CharSequence cha, float currentSize) {
        TextPaint paint = new TextPaint();
        paint.setTextSize(currentSize);
        return  paint.measureText(cha, 0, cha.length());
 }

currentSize was setting directly before,then I gave currentSize parameter by getting textSize from TextView, currentSize=tv.getTextSize(); Also I did not convert display width to dp.Now it returns result in pixels format.Hope it helps someone...

Upvotes: 2

Related Questions