Skip to content

Adding Support for Emojis

Andreas edited this page Feb 1, 2017 · 6 revisions

This section is based on a request to support emojis in RichTextFX (https://github.com/TomasMikula/RichTextFX/issues/427).

There are two approaches how to support inline emojis, like :-D or :-):

  • Embedd them as images using the custom objects approach
  • Use the corresponding UNICODE codepoints

Embedding as custom objects

The emojis can be made available as images and then embedded using the custom object approach. See Implementing custom objects for more information.

Using the UNICODE codepoints

UNICODE contains codepoints for emojis and other symbols starting at U+1F600. By adding characters for those codepoints into a text segment, the emojis can be directly embedded into any text.

However, an appropriate font is required which contains the necessary glyphs to render those codepoints. The following example uses the JavaKeywords demo to show the approach.

First, let's add the following line to JavaKeywords.java to render a Euro character (U+20AC) and an emoji (U+1F600) (note that the UNICODE codepoints for emojis require a surrogate pair since they are encoded with more than 16 bit):

...
"/* T\u20acs\uD83D\uDE00t */",
"public class Foo extends Bar implements Baz {",
...

Without further modifications, the emoji will be rendered as square:

image

If any character is rendered as square, this usually indicates that the used font does not contain the necessary glyph for the corresponding codepoint.

Let's apply the following modifications to the JavaKeyword demo (see also http://stackoverflow.com/a/16866962/1611055):

  • We need to downloaded an appropriate font (for example, https://github.com/MorbZ/OpenSansEmoji/blob/master/OpenSansEmoji.ttf) and put it in the org.fxmisc.richtext.demo package

  • In the demo's start method, we add code to load the font: Font.loadFont(JavaKeywords.class.getResource("OpenSansEmoji.ttf").toExternalForm(), 10);

  • In the java-keywords.css file, we are adding

    .paragraph-box {
    	-fx-font-family: "OpenSansEmoji";
    }
    

    so that the font is being applied to the paragraph box nodes.

Now, the text is rendered like this:

image

Note that all characters are now rendered with the OpenSansEmoji font. If this is not desired, the text which contains emojis can be styled with a different style (RichTextFX then puts those characters into their own segment). Then only the style for the emoji segments must use the special font.