8
votes

I am currently drawing text on Canvas while using external (non-standard) font, loaded from TTF file. I want to enable kerning for the text I am displaying.

What I want to know is if there is a possibility to read kerning pairs from typeface using Android API.

2
This older question (but with answers as recent as last year) suggest the kern tables are not exposed into Java. Is "manually" parsing the raw file data a viable option? (Noting that there are several different table formats, all equally atrocious...)Jongware
thanks, Jongware. I do not mind parsing *.ttf files providing there is some information on where to look for kerning pairs (I'm usually a bit afraid of atrocious formats).Alex Semeniuk
That would be in the OpenType specifications, to be exact in The Kerning Table. Definitely not for the faint of heart; and if you are really unlucky, the font you used is a Type 1 type and so you'd need to parse the GPOS subtable, which is yet magnitudes more difficult... (This may well be the very reason the programmers of Canvas' drawText simply did not bother ...)Jongware
Thanks. I'll experiment with this when I have some spare time.Alex Semeniuk
There is no Android API to get the kerning table or parse a TTF file. However, I have slimmed down and ported apache fop and it should be able to accomplish what you want. I can't find a TTF that has kerning. Will you please link to a font using kerning?Jared Rummler

2 Answers

9
votes

What I want to know is if there is a possibility to read kerning pairs from typeface using Android API.

There is no public API to read kerning pairs from a TTF file. However, I pulled the relevant code from Apache FOP and you can read the kerning pairs using this library.

Example usage:

TTFFile file = TTFFile.open(getAssets().open("fonts/font.ttf"));
Map<Integer, Map<Integer, Integer>> kerning = file.getKerning();

You can also retrieve other metadata. Example:

TTFFile ttfFile = TTFFile.open(new File("/system/fonts/Roboto-Regular.ttf"));

String name = ttfFile.getFullName();             // "Roboto Regular"
String family = ttfFile.getSubFamilyName();      // "Regular"
int fontWeight = ttfFile.getWeightClass();       // 400
String copyright = ttfFile.getCopyrightNotice(); // "Font data copyright Google 2014"

I want to enable kerning for the text I am displaying.

See:

How to adjust text kerning in Android TextView?

setLetterSpacing(float)

0
votes

I was willing to use the parser described above using standard Java on Windows. If anyone wants to do it, one needs to use Rectangle instead of Rect. This is just a minor conversion. I also eliminated the directory jaredrummler because it was a bit too long (I kept the copyright comments in the beginning of the files, though). But there are two TTFFile classes in this parser. This code:

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

Only works if you import the correct class file:

import com.fontreader.truetype.TTFFile;

Finally, the code works but the kerning pairs returned don't work with the paths you convert using:

void vectorize(Path2D.Float path, String s) {
    PathIterator pIter;
    FontRenderContext frc = new FontRenderContext(null,true,true);
    GlyphVector gv;
    Shape glyph;
    gv = font.createGlyphVector(frc, s);
    glyph = gv.getGlyphOutline(0);
    pIter = glyph.getPathIterator(null);
    while (!pIter.isDone()) {
        switch(pIter.currentSegment(points)) {
        case PathIterator.SEG_MOVETO:
            path.moveTo(points[0], points[1]);
            break;
        case PathIterator.SEG_LINETO :
            path.lineTo(points[0], points[1]);
            break;
        case PathIterator.SEG_QUADTO :
            path.quadTo(points[0], points[1], points[2], points[3]);
            break;
        case PathIterator.SEG_CUBICTO :
            path.curveTo(points[0], points[1], points[2], points[3], points[4], points[5]);
            break;
        case PathIterator.SEG_CLOSE :
            path.closePath();
        }
        pIter.next();
    } 
}

And lengths recovered by lens in the following code:

double interchar = fontsize * 0.075;
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], tx[i], 0f);
    lens[i] = glyphs[i].getBounds2D().getWidth() + interchar;
}

Just to be clear, I display the glyphs using fill in Graphics2D and I translate using the lengths above added to the kerning displacements returned by the library Apache FOP as suggested above, but the result is horrible. The fontsize is standard 1000 as suggested in this discussion and interchar results in 75, after multiplying by the font size. All this seems correct but my manual kerning pairs look far much better than using the kerning pairs from the ttf file.

Is there anyone trained with this library to be able to tell how we are supposed to use these kerning pairs?

Sorry for diverting slightly from the original question but this might complete the information since once one reads the kerning pairs how one uses them correctly on either Windows or Android?