Tip: How to print unicode characters in openFrameworks 0.8.2

OF 0.8.2 has added support for unicode characters, some of you may ask how to print them. Since most of the C++ libraries rarely bother to support wide strings or wide characters, you should convert integer key of keyPressed() event to std::string. Here’s how you can do that, you’ll need Boost.Locale header only library:

#include <boost/locale.hpp>

void ofApp::keyPressed(ofKeyEventArgs& key)
  u32string ustr; ustr = (char32_t)key.key;
  string uchar = boost::locale::conv::utf_to_utf<char>(ustr);

  bool isCharPressed = (key.keycode >=  32 && key.keycode <=  96) ||
                       (key.keycode >= 320 && key.keycode <= 334);

  if (isCharPressed) cout << uchar << endl;

Here’s a little app demonstrating unicode (English, Russian and Katakana) characters drawing with ofxTrueTypeFontUC addon:



Little update: I’ve changed the example, now it uses ofxTrueTypeFontUC. The advantages of this change are:

  • While ofxFontStash is fast and all that, it uses deprecated OpenGL calls and because of that it can’t be used with ofGLProgrammableRenderer. ofxTrueTypeFontUC is written with openFrameworks so that it adapts to the current renderer.
  • ofxTrueTypeFontUC is not tied to ofxUnicode addon.
  • The whole addon is basically two files which you can include easily in your projects.

The example is moved to github and updated for upcoming OF 0.9.0, also I’ve added isCharPressed bool which checks if user pressed a character button and not modifier or function key, - it’s useful for apps that require typing.