harfbuzz_rs
v2.0.1
harfbuzz_rs是Harfbuzz的高级接口,使用Rust以安全的方式暴露其最重要的功能。
Harfbuzz是用于执行复杂文本布局的库。它不执行任何图纸。这是一个低级操作。如果您想简单地在屏幕上绘制一些文本,则应该选择另一个高级库。但是,如果要构建一个库,以在某些画布上绘制文本或需要对高级文本布局进行大量控制,那么这是可以使用的正确库。
要形成简单的文本字符串,您只需从字体文件创建Font ,请填充一些文本的Buffer并调用shape函数。
use harfbuzz_rs :: * ;
let path = "path/to/some/font_file.otf" ;
let index = 0 ; //< face index in the font file
let face = Face :: from_file ( path , index ) ? ;
let mut font = Font :: new ( face ) ;
let buffer = UnicodeBuffer :: new ( ) . add_str ( "Hello World!" ) ;
let output = shape ( & font , buffer , & [ ] ) ;
// The results of the shaping operation are stored in the `output` buffer.
let positions = output . get_glyph_positions ( ) ;
let infos = output . get_glyph_infos ( ) ;
// iterate over the shaped glyphs
for ( position , info ) in positions . iter ( ) . zip ( infos ) {
let gid = info . codepoint ;
let cluster = info . cluster ;
let x_advance = position . x_advance ;
let x_offset = position . x_offset ;
let y_offset = position . y_offset ;
// Here you would usually draw the glyphs.
println ! ( "gid{:?}={:?}@{:?},{:?}+{:?}" , gid , cluster , x_advance , x_offset , y_offset ) ;
}这应该打印出类似于以下内容的内容:
gid41=0@741,0+0
gid70=1@421,0+0
gid77=2@258,0+0
gid77=3@253,0+0
gid80=4@510,0+0
gid1=5@227,0+0
gid56=6@874,0+0
gid80=7@498,0+0
gid83=8@367,0+0
gid77=9@253,0+0
gid69=10@528,0+0
gid2=11@276,0+0
默认情况下, x_advance , x_offset , y_advance和y_offset的值都在所谓的字体单元中给出。通过调用face.upem()您可以获得特定face的每个em字体单元数量。该upem升值可用于将进步和偏移扩展到给定的字体大小。例如,如果要在16点(PT)大小上显示字体,则意味着1 EM = 16 pt 。在此示例中,要将一个值(例如x_advance )转换为从字体单元转换为点,我们计算((x_advance * font_size) as f64) / (upem as f64) ,其中font_size = 16是一个可变的,可以在点中指定字体大小。
请注意,Harfbuzz在内部也支持缩放字体自身(使用font.set_scale(...)等),但我认为,如上所述,更容易扩展结果。
该板条箱经过测试,可与Harfbuzz版本2.0及更高版本一起使用。较旧的版本也可能起作用。我建议您静态地链接由harfbuzz-sys Crate提供的Harfbuzz库,该库始终是最新的。
如果要使用RustType作为字体函数,则可以启用rusttype功能。