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)