How to use kerning pairs extracted from a TTF file to correctly show glyphs as Path2D in Java?

后端 未结 2 1200
孤城傲影
孤城傲影 2021-01-25 13:38

This question is about recovering glyph font information in Java and it is related to a question posted here. For more details please check the question and ans

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 14:33

    Problem solved!

    Recalling that to open the file and to obtain the kerning pairs one needs this code, using the library Apache FOP:

    TTFFile file;
    File ttf = new File("C:\\Windows\\Fonts\\calibri.ttf" );
    try { file = TTFFile.open(ttf); }
    catch (IOException e) {e.printStackTrace(); }
    Map> kerning = file.getKerning();
    

    The following piece of code to vectorize the glyphs is correct now:

    Font font = new Font("Calibri", Font.PLAIN, 2048);
    int size = '}' - ' ' + 1;
    Path2D.Float[] glyphs = new Path2D.Float[size];
    //double[] lens = new double[size];
    String chars[] = new String[size];
    int i; char c; 
    char[] s = { '0' };
    for (i = 0, c = ' '; c <= '}'; c++, i++) { s[0] = c; chars[i] = new String(s); }
    for (i = 0; i < size; i++) {
        vectorize(glyphs[i] = new Path2D.Float(), chars[i]);
        //lens[i] = glyphs[i].getBounds2D().getWidth();
    }
    

    Notice that now the font size is 2048 which is the unitsPerEm for this particular font. This value is given by the HEAD tag in the font file as explained here.

    Notice that the widths cannot be given by the array lens and code commented out above. It has to be read from the file. Using int width = getCharWidthRaw(prev) from Apache FOP, where prev is the previous character, width is the raw width of the character as written in the file. This value has to be added to the kerning pair value that can be obtained in the map kerning.

    The map is used this way: kerning.get(prev) which returns another map containing the characters and kerning values to be added. If the character to be shown next is found in this map, the corresponding value is added to width. If not found, or if null is returned, there is no kerning value for this pair.

    Here it is a text to show the kerning now works.

提交回复
热议问题