Kivy是否支持Light与Condensed字体?如何调用单TTF内的字体变体?
解决Kivy调用字体变体(Light/SemiCondensed)的问题
Kivy默认的[font]标记仅支持指定字体系列或字体文件,无法直接调用Light、Condensed这类字重/字宽变体。对于像Bahnschrift这种将多个变体打包在单个TTF文件中的字体,你可以通过FontProperties类精准指定所需的字体属性。
具体实现步骤
1. 在KvLang中导入FontProperties
在kv文件开头添加导入语句,引入Kivy的字体属性类:
2. 为Label设置字体属性
通过font_properties属性,指定字体系列、字重(light)和字宽(semi_condensed):
修改后的test.kv代码:
#:kivy 2.1.0 #:import FontProperties kivy.core.text.fonts.FontProperties <Testkv>: Label: text:'hello' font_size: 44 font_properties: FontProperties(family='Bahnschrift', weight='light', stretch='semi_condensed')
3. 可选:通过Python代码设置
如果你更倾向于在Python代码中配置,可以在Testkv类中为Label绑定字体属性:
修改后的test.py代码片段:
from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.core.text.fonts import FontProperties class Testkv(FloatLayout): def __init__(self, **kwargs): super().__init__(**kwargs) label = self.ids.my_label # 需先在kv中给Label设置id: my_label label.font_properties = FontProperties( family='Bahnschrift', weight='light', stretch='semi_condensed' ) class testApp(App): def build(self): return Testkv() if __name__ == '__main__': testApp().run()
对应的kv文件需添加id:
#:kivy 2.1.0 <Testkv>: Label: id: my_label text:'hello' font_size: 44
关键参数说明
family:指定字体系列名称(这里是Bahnschrift,确保字体已安装在系统中)weight:可选值包括'thin'、'light'、'normal'、'bold'等,或对应的数值(如300对应light)stretch:可选值包括'condensed'、'semi_condensed'、'normal'、'expanded'等,用于指定字宽变体
这样就能正确渲染Bahnschrift Light SemiCondensed字体了。
内容的提问来源于stack exchange,提问作者Chene
相关产品推荐
相关产品推荐

