Wolfgang Schreurs
Wolfgang Schreurs

Reputation: 11834

Changing the color of individual characters in a glyph

As I understand it, a string contains glyphs and a glyph might consist of individual characters. For me this is a problem, as I would like to change the color of some diacritics in a string.

Let's say we have the following string:

วาีม

For this string I would like to make the consonants a different color as it's diacritic. I.e.: I want a different color for วาม and .

From my tests it seems that I am only able to color individual glyphs. It seems I can not change the color at a character (diacritic) level. Some example code:

let text = NSMutableAttributedString(string: "วาีม")
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSMakeRange(0, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(1, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.green, range: NSMakeRange(2, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSMakeRange(3, 1))
label.attributedText = text

The above would render as follows:

enter image description here

As can be seen the diacritic is not rendered with a green color.

Does anyone know if there is some way to achieve the result I want?

Upvotes: 3

Views: 566

Answers (2)

Ken Thomases
Ken Thomases

Reputation: 90551

I doubt you'll find a good way to do this. The glyph for าี in the font is a completely different thing than the glyph for . For example, in the Thonburi font on my Mac, the former is glyph 1507 and the latter is glyph 78. Each glyph entry in the font is a completely separate little description of how to draw the glyph. For the combined glyph, the diacritic is not a separate thing. The system has no way to know when it's drawing the base character and when it's drawing the diacritic. It's just drawing one thing. So, it can't apply different colors.

I'm completely unfamiliar with Thai, so I'm just speculating for this next part, although it's certainly true for some languages: I suspect there are glyphs for combining sequences which are radically different from what you'd get by just overlaying the component parts on top of each other. So, even in principle, it's not clear that there's a visually separable diacritic shape vs. the base character.

Upvotes: 2

Williham Totland
Williham Totland

Reputation: 29009

An alternative is to put two labels on top of one another; one containing the text with the diacritics in the colour you want for the diacritics; one on top of it with the same text but without the diacritics, in the colour you want for the text.

When rendering, the identical bits of the text should cancel out exactly, leaving you with text and diacritics in the right colours.

Upvotes: 1

Related Questions