Check if custom font can display character

Update:
If you’re coding for API level 23 or above please use Paint.hasGlyph() as mentioned in the answer by Orson Baines. Otherwise see my original answer below.


As you mentioned in your own answer there is no built in methods available for checking this. However if you have some control over what string/characters you want to check, it is actually possible to do this with a slightly more creative approach.

You could draw a character that you know are missing in the font you want to check and then draw a character that you want to know if it exists, and then finally compare them and see if they look the same.

Here is a code sample that illustrates how I implemented this check:

public Bitmap drawBitmap(String text){
    Bitmap b = Bitmap.createBitmap(BITMAP_WIDTH, BITMAP_HEIGHT, Bitmap.Config.ALPHA_8);
    Canvas c = new Canvas(b);
    c.drawText(text, 0, BITMAP_HEIGHT / 2, paint);
    return b;
}

public byte[] getPixels(Bitmap b) {
    ByteBuffer buffer = ByteBuffer.allocate(b.getByteCount());
    b.copyPixelsToBuffer(buffer);
    return buffer.array();
}
public boolean isCharacterMissingInFont(String ch) {
    String missingCharacter = "\u0978"; // reserved code point in the devanagari block (should not exist).
    byte[] b1 = getPixels(drawBitmap(ch));
    byte[] b2 = getPixels(drawBitmap(missingCharacter));
    return Arrays.equals(b1, b2);
}

There are some important limitations to keep in mind with this method:

  • The character you check (argument to isCharacterMissing) must be non whitespace (can be detected by using Character.isWhitespace()). In some fonts missing characters are rendered as whitespace, so if you would compare a whitespace character that exists it would incorrectly be reported as a missing character in fonts like these.
  • The missingCharacter member must be a character that is known to be missing in the font to be checked. The code point U+0978 that I am using is a reserved code point in the middle of the Devanagari Unicode block so it should currently be missing in all Unicode compatible fonts, however in the future when new characters are added to Unicode this code point might be assigned to a real character. So this approach is not future proof, but if you supply the font yourself you can make sure you are using a missing character whenever you change the font of your application.
  • Since this check is done by drawing bitmaps and comparing them it’s not very efficient so it should only be used to check a few characters and not all strings in your application.

Update:

The solution to look at U+0978 did not work long as pointed out by others. That character was added in the Unicode 7.0 release in June 2014. Another option is to use a glyph that exists in unicode but that is very unlikely to be used in a normal font.

U+124AB in the Early Dynastic Cuneiform block is probably something that doesn’t exist in many fonts at all.

Leave a Comment