Tuesday 23 July 2024

Displaying Emojis in Windows based consoles

This article will show you how you can get started with showing emojis in Windows based consoles. For an initial peek - Here is a video showing the available Emojis on Windows system I found using Nerd Font Caskaydia Cove mono font glyphs :


First off, some code showing how we can output Emojis ! We will list emojis and their code point value, a hexadecimal integer value that is used to get the correct char that represents an Emoji. Here is the console app.
Program.cs


using System.Text;

Console.OutputEncoding = System.Text.Encoding.UTF8;

var sb = new StringBuilder();
int emojisAdded = 0;
const int EMOJIS_PER_LINE = 10;
int codePoint = 0x1F300;

// Define the ranges of emojis
int[][] emojiRanges = new int[][]
{
            new int[] { 0x1F300, 0x1F5FF },
            new int[] { 0x1F600, 0x1F64F },
            new int[] { 0x1F680, 0x1F6FF },
            new int[] { 0x1F900, 0x1F9FF },
            new int[] { 0x1FA70, 0x1FAFF }
};

foreach (var emojiRange in emojiRanges)
{

    for (codePoint = emojiRange[0]; codePoint <= emojiRange[1]; codePoint++)
    {
        string emoji = char.ConvertFromUtf32(codePoint);
        sb.Append(emoji);
        emojisAdded++;
        if (emojisAdded % EMOJIS_PER_LINE == 0)
        {
            Console.WriteLine($"{sb.ToString()} {codePoint - 9:X}- {codePoint:X}");
            sb.Clear();
        }
    }

    Console.WriteLine(sb.ToString() + " " + (codePoint - 9).ToString("X") + (codePoint.ToString("X"))); //print remaining emojis

}


We use some known ranges of code points, hexadecimal valued integers where we know we in UTF-8 will find Emoji. We set up UTF-8 as the Console output encoding. We will use the method char.ConvertFromUtf32 here and the font will render the Emoji as a Glyph. Please note that not all consoles support Emojis in Windows ! We use Windows Terminal and I have set up a font that supports emojis, 'CaskaydiaCove Nerd Font Mono'. You can find the font and .ttf files to install on Github, just search for "Nerd font" and you will find it here :

https://github.com/ryanoasis/nerd-fonts/releases

If we compile the program and open it in Windows Terminal, you should get something similar to what shown below. I see there are issues on the very last emojis as they are not outputted correct, in the group "Symbols and Pictographs Extended-A". Emoticons: U+1F600 to U+1F64F Miscellaneous Symbols and Pictographs: U+1F300 to U+1F5FF Transport and Map Symbols: U+1F680 to U+1F6FF Supplemental Symbols and Pictographs: U+1F900 to U+1F9FF Symbols and Pictographs Extended-A: U+1FA70 to U+1FAFF Here are screenshots from the Emoji demo, ten Emojis are shown per row ! The "code point" integer range for each row is displayed to the right.

Share this article on LinkedIn.

No comments:

Post a Comment