I have the same idea and need. No library function that I know of which will give us what we need. I ended up working something out that works but is not ideal. You can see my code below.
The only way I could find out how long a string would appear on screen was through a call to textObj.width but you can get this only after you call the display.newRetinaText().
So in a nutshell you use display.newRetinaText and put the text up and then see if its >= than the width you don’t want to exceed. If its too long then you use string.sub to keep shortening it in a while loop until its short enough. Downside of this approach is that you need to keep updating textObj.text which in return updates the display.newRetinaText in each iteration to get the new width. This must be CPU intensive. I shorten the text by 2 chars each time to make it go down faster with less impact. Seems to work ok on the simulator. Will try next on the devices to see if the performance is acceptable.
Anyways, here goes. If you improve on it please post here so I and others can benefit too. I also appreciate any other input from anyone who might have a better way to go about this. Thanks much!
local screenWidth = display.contentWidth local textObj = display.newRetinaText( myOriginalText, 0, 0, "Helvetica", 14 ) local shortenedText = myOriginalText if ( textObj.width \>= (screenWidth - 20) ) then while ( textObj.width \>= (screenWidth - 20) ) do print(textObj.width) print(shortenedText) shortenedText = string.sub(shortenedText, 1, (string.len(shortenedText) - 2)) textObj.text = shortenedText end shortenedText = shortenedText .. "..." textObj.text = shortenedText end
Edit - some improvements to the code. Realized I don’t need to keep calling display.newRetinaText() over and over. I can simply update the textObj.text and get the new width with textObj.width. Seems to work faster and cleaner.