freetypeで読み込んでcairoで描画

文字のレイアウトとutf8からunicodeへの変換はcairoに任せられる。

#include <iostream>
#include <cassert>

#include <ft2build.h>
#include FT_FREETYPE_H
#include <cairo-ft.h>

class FreeType
{
  FT_Library library_;
  FT_Face face_;
  int error_;

  public:
  FreeType(const char *file, int index=0)
  {
    error_=FT_Init_FreeType(&library_);
    if(error_){
      return;
    }
    error_=FT_New_Face(library_, file, index, &face_);
    if(error_){
      return ;
    }
  }

  ~FreeType()
  {
    error_=FT_Done_Face(face_);
    assert(error_==0);
    error_=FT_Done_FreeType(library_);
    assert(error_==0);
  }

  int getError(){ return error_; }

  FT_Face& getFace(){ return face_; }
};

int main(int argc, char **argv)
{
  if(argc<2){
    std::cout << "usage: " << argv[0] << " {string}" << std::endl;
    return 1;
  }

  const char *fontFile="mikachanfont-8.9/fonts/mikachan.ttf";
  FreeType freetype(fontFile);
  if(freetype.getError()){
    std::cout << "fail to load: " << fontFile << std::endl;
    return 1;
  }

  // cairo
  cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 390, 60);
  cairo_t *cr = cairo_create(surface);

  // set freetype font
  cairo_set_font_face(cr
      , cairo_ft_font_face_create_for_ft_face(freetype.getFace(), 0));
  // draw text
  cairo_set_font_size(cr, 40.0);
  cairo_move_to(cr, 10.0, 50.0);
  cairo_show_text(cr, argv[1]);

  cairo_surface_write_to_png(surface, "image.png");

  cairo_destroy(cr);
  cairo_surface_destroy(surface);
  return 0;
}
$ g++ `pkg-config cairo-ft --cflags --libs` main.cpp