How to know the preferred display width (in columns) of Unicode characters?

后端 未结 5 2045
说谎
说谎 2020-12-23 18:10

In different encodings of Unicode, for example UTF-16le or UTF-8, a character may occupy 2 or 3 bytes. Many Unicode applications doesn\'t t

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-23 18:27

    Regarding "Or any Java library function to calculate the display width?": if there is one I've never found it.

    The simplest method of calulating the width of a character / string is to write it in the GNU unicode font ( http://unifoundry.com/unifont.html ) & measure the character width. Not clean, but so far it's worked for every encoding I can think of.

    FWIW here's what I do:

    java.awt.font.Font MONOSPACEFONT = Font.createFont(Font.TRUETYPE_FONT, 
        new File("unifont-5.1.20080907.ttf"));
    
    java.awt.font.FontRenderContext FRC = new FontRenderContext(null, true, true);
    
    int charWidth =  (int) (2.0*((java.awt.geom.Rectangle2D.Float) 
        MONOSPACEFONT.getStringBounds(stringToMeasure, FRC)).width);
    

    ... this should work pretty much anywhere you deploy your JVM (it runs fine in a headless environment).

提交回复
热议问题