Formatted display.newText

Hi,

I have a string where I want to format part of it, basically, change the color of that part inside the display.newText.

Let us take this example to make it clear.

textString = "Hello this is Mike. My name is Mike."
newString = string.gsub( textString, "(Mike)",  "{a}Mike{/a}" )
print( newString ) //  Hello this is {a}Mike{/a}. My name is {a}Mike{/a}.


local myText = display.newText( newString, 100, 200, native.systemFont, 12 )
myText:setFillColor( 1, 0, 0.5 )

How can I change “Mike” to be a different color?
Any hints are more than appreciated!

That’s good question. I remember coming up against this a while back and deciding that there was no easy method. I think I used HTML text to add color in one situation and multiple text objects (not ideal) in another.

1 Like

Here are some libraries that I bookmarked earlier:

1 Like

@sporkfin Thank you. HTML is fine but I am trying to do that with ‘display.newText’.

@bgmadclown I know the first one but it needs lots of tweakings to achieve the result I wanted. I will look into the other module and update the status later. Thank you!

What you need is to split your Text into a few Texts where one of them has bold font, different colour, etc. Before that find width of a space symbol to use as a margin between the Texts.

For developers: it would be good to have RichTextBox … :slight_smile:

1 Like

@Andrey5045 Splitting the text is not the hard part but doing the math for the margin is. I tried doing this approach and it worked but was not an ideal solution as sometimes the text is off by some pixels.

In fact, the second library @bgmadclown mentioned did the trick too. The only thing I wish it supported is RTL text, but that’s fine. So thank you @bgmadclown for bringing that up!

1 Like

Glad it helped :slight_smile:

Yep, definitely. We had a feature request for that back in Corona SDK days. Still waiting :slight_smile:

Here is the algo, I used to create a module that sets text justified.

Let’s say
TextAreaWidth_int = (displayWidth - margin*2)

  1. Put all the words in to a table,
    something like this:
local words_T = {}
for a_str in long_text:gmatch("[^%s]+") do
	words_T[#words_T + 1] = a_str
end
  1. Start creating display.newText by adding a word by word. Once it is wider than TextAreaWidth_int, you may know how many words can fit into a line. E.g. on the 5th word the line becomes wider than TextAreaWidth_int, it means you can fit 4 words.

  2. Now you create display.newText out of each word put together without spaces. A little bit of more math and you can get the width of space that will be set in your line so that it would be justified.

If you do not want to justify your text, then your approach is just the same - grow your display.newText until you find the proper number of words that can fit.

1 Like