0

I need the width and height of the enclosing bounds of a string with limit on width or on height. Found two method, but they does not exactly what I am looking for.

Paint .measureText() .getTextBounds()

How can I set a limit, i.e. I do not want the bound's width be bigger than 300px?

In iOS NSString's boundingRect method calculate this, or the sizeToFit.

János
  • 32,867
  • 38
  • 193
  • 353
  • When using Paint, you paint the text yourself. So you can paint it letter by letter or word by word and if the measuredText of your text + the next letter is exceeding 300px you just don't paint it or switch the line. – loshkin Oct 10 '16 at 10:07
  • I need to put in "\n" characters? – János Oct 10 '16 at 10:09
  • 1
    no, you dont `need to put in "\n" characters`: read about `android.text.Layout` class – pskink Oct 10 '16 at 10:27
  • @pskink I see, it is like constraints in iOS, is it possible to set the **height** parameter is the **variing bonds component** in layout XML? – János Oct 10 '16 at 10:34
  • no, it lays out the input text, with the fixed width: just like one column in the newspaper - all you need is to pass your text and maximum width and the height of this layout will be calculated based on text and max width – pskink Oct 10 '16 at 10:36

2 Answers2

0

I think you not fully understand what Paint.measureText doing.
This method just calculates width of text, using Paint inner params. If you want to limit your text, for example ellipsize text you can use this thread

Otherwise, Paint.getTextBounds needs in Rect object, that this method will fill. But no limitation here.

Community
  • 1
  • 1
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
  • `ellipsize` will truncate text. I need to calculate the needed height for a fixed width, if text, font and fontsize is known. Do you know how to do it in Android? – János Oct 10 '16 at 10:25
0

Found here the answer. Need View.MeasureSpec to calculate height f width is limited.

Community
  • 1
  • 1
János
  • 32,867
  • 38
  • 193
  • 353
  • @pskink nothing, but `View.MeasureSpec` can calculate required height if width is limited – János Oct 10 '16 at 11:06
  • so probably your problem is a typical [XY Problem](http://xyproblem.info/), what do you want to achieve actually? – pskink Oct 10 '16 at 11:10
  • @pskink I think my PROBLEM was quite specific. Refered two paint method to show I put effort to find solution. – János Oct 10 '16 at 11:15