0

I need to set font size for a multiline label dynamically depending on its container dimensions. The whole text should fit into the container evenly. If text is short the font should be bigger, if long - smaller. Also I would like to set maximum and minimum allowed font size and maximum allowed lines number. This means that if text is too long and it can not fit into the container with given minimum font size and maximum lines number it should be truncated with ellipsis.

I managed to do so on iOS, but could not achieve the same on Android.

Here is the iOS code:

function setTextForLabelIOS( label: any, maxFontSize: number, minFontSize: number, maxLines: number ) {

    let numLines: number = 1
    const font = label.font // UIFont

    const textSize = NSString.stringWithString( label.text ).sizeWithAttributes( <any>{ [ NSFontAttributeName ]: font } )
    const textWidth = Math.ceil( nsUtils.layout.toDevicePixels( textSize.width ) )
    const textHeight = Math.ceil( nsUtils.layout.toDevicePixels( textSize.height ) )

    while ( ( ( textWidth / numLines ) / ( textHeight * numLines ) > labelContainerWidth / labelContainerHeight )
    && numLines < maxLines ) {
        numLines += 1
    }

    label.adjustsFontSizeToFitWidth = true
    label.numberOfLines = numLines
    label.minimumScaleFactor = minFontSize / maxFontSize
}

(iOS solution is based on https://stackoverflow.com/a/44103978/3595434)

terreb
  • 1,417
  • 2
  • 23
  • 40
  • It would help if you describe what you tried to do, as well as what the code you pasted here does. – pkanev Sep 12 '17 at 11:02
  • @pkanev, I edited the description. Hope it explains now. – terreb Sep 12 '17 at 11:11
  • Unless you want to extend your own android TextView widget in NativeScript and use it instead of the Label provided by the tns-core-modules, you could look at this answer - https://stackoverflow.com/a/7288362/6408287 You get the label's underlying android widget by accessing `labelInstance.android` – pkanev Sep 12 '17 at 11:23
  • Thank you for the link. The problem with that solution is that it works only for one line text. I would like it also sets optimal number of lines with given max and min font size like the iOS solution does. – terreb Sep 13 '17 at 11:18
  • I actually saw that thread before and there are some solutions that should do what I need (they seems deal with multiline text), but I haven't had success implementing them getting different Android and java errors. That's why I'm looking for a Nativescript specific Android solution here. Thanks. – terreb Sep 13 '17 at 11:25
  • Post on the forums, people there will be more than happy to help you with extending your own textview. – pkanev Sep 13 '17 at 11:55

0 Answers0