rougier / freetype-py

Python binding for the freetype library
Other
298 stars 88 forks source link

How to change the default encoding? #191

Closed lp20010415 closed 1 month ago

lp20010415 commented 1 month ago

like this code, it is default encoding is "UTF-8"

font = freetype.Face(r"C:\Windows\Fonts\simsun.ttc")
for char_code, glyph_index in font.get_chars():
    print(char_code, glyph_index)

if i want to use "GB18030" that how can i what to do? or i want to use customized encoding.

HinTak commented 1 month ago

If the font contains a GB18030 charmap, You use FT_Set_Charmap or FT_Set_Charmap , with argument FT_ENCODING_GB2312 (upstream seems to have changed it to FT_ENCODING_PRC). However, I have a quick look at simsun.ttc itself, and it does not have a GB18030 charmap. In that case, you transcode your input with input.decode("GB18030") before you pass to font.get_chars(). This also works in general for most recent fonts. (To be honest, the former is only recommended for very old fonts from the 90's).

HinTak commented 1 month ago

If my answer wasn't clear, your question happens to be invalid for that particular font - with some fonts from the 90's which has a GB charmap, you can set the default charmap to that. But with simsun.ttc (or the few versions of that particular microsoft font I have on my hard disk at the moment), which only have unicode charmaps, you just have to transcode your input via the usual python encoding/decoding routines (outside of freetype-py), before you invoke freetype-py routines.

I have a bunch of such old fonts with Copyright 1994-1997, Arphic Technology Co., Ltd. from the 90's , but recent fonts simply don't have GB charmaps anymore.

lp20010415 commented 1 month ago

如果我的答案不清楚,那么您的问题恰好对于该特定字体无效 - 对于 90 年代的某些具有 GB 字符映射的字体,您可以将默认字符映射设置为该字体。但是对于simsun.ttc(或者我目前硬盘上的特定微软字体的几个版本),它只有unicode字符映射,你只需要通过通常的python编码/解码例程(在freetype-py之外)对你的输入进行转码),在调用 freetype-py 例程之前。

我有一堆Copyright 1994-1997, Arphic Technology Co., Ltd. 90 年代的旧字体,但最近的字体根本没有 GB 字符映射。

OK,I get it.Thanks for you reply.

HinTak commented 1 month ago

In the example directory, there are two code examples, font-info.py and ftdump.py, both of which shows info of font file, and both contains the available charmaps.

I just updated them on some cosmetic issues, unrelated to the charmap info. They haven't been used much since python 2 days, so some of print statements needs updating.