A simple shaping example

This example shapes a UTF-8 string with a font from a file. See the section called “Detecting failures” for more on checking errors.

  1. Create a buffer and put your text in it.

    #include <hb.h>
    
    hb_buffer_t *buf;
    buf = hb_buffer_create();
    hb_buffer_add_utf8(buf, text, -1, 0, -1);
    
  1. Set the script, language and direction of the buffer.

    // If you know the direction, script, and language
    hb_buffer_set_direction(buf, HB_DIRECTION_LTR);
    hb_buffer_set_script(buf, HB_SCRIPT_LATIN);
    hb_buffer_set_language(buf, hb_language_from_string("en", -1));
    
    // If you don't know the direction, script, and language
    hb_buffer_guess_segment_properties(buf);
    
  1. Load the first face from a font file and create a font for shaping. The face constructor returns NULL if it cannot read the file or find the requested face.

    hb_face_t *face = hb_face_create_from_file_or_fail(filename, 0);
    if (!face) {
        hb_buffer_destroy(buf);
        return 1;
    }
    hb_font_t *font = hb_font_create(face);
    hb_face_destroy(face);
    if (font == hb_font_get_empty()) {
        hb_buffer_destroy(buf);
        return 1;
    }
    
  1. Shape the text. For display, use the glyphs HarfBuzz produces even if an adversarial font reaches a shaping limit. You can skip the hb_buffer_allocation_successful() check and continue rendering.

    hb_shape(font, buf, NULL, 0);
    
  1. Get the glyph and position information.

    unsigned int glyph_count;
    hb_glyph_info_t *glyph_info    = hb_buffer_get_glyph_infos(buf, &glyph_count);
    hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(buf, &glyph_count);
    
  1. Iterate over each glyph.

    hb_position_t cursor_x = 0;
    hb_position_t cursor_y = 0;
    for (unsigned int i = 0; i < glyph_count; i++) {
        hb_codepoint_t glyphid  = glyph_info[i].codepoint;
        hb_position_t x_offset  = glyph_pos[i].x_offset;
        hb_position_t y_offset  = glyph_pos[i].y_offset;
        hb_position_t x_advance = glyph_pos[i].x_advance;
        hb_position_t y_advance = glyph_pos[i].y_advance;
      /* draw_glyph(glyphid, cursor_x + x_offset, cursor_y + y_offset); */
        cursor_x += x_advance;
        cursor_y += y_advance;
    }
    
  1. Tidy up.

    hb_buffer_destroy(buf);
    hb_font_destroy(font);
    

This example shows enough to get us started using HarfBuzz. In the sections that follow, we will use the remainder of HarfBuzz's API to refine and extend the example and improve its text-shaping capabilities.