如何使用 KIVY API 计算特定字体和大小的字符串长度(以像素为单位)?

How to calculate the length of a string in pixels for specific font and size, using KIVY API?

我想使用 KIVY 查找默认或指定字体和大小的字符串长度(以像素为单位)。

我发现了一个类似的问题, 使用 PIL 的解决方案,但我无法解决:

from PIL import ImageFont
font = ImageFont.truetype('times.ttf', 12)
size = font.getsize('Hello world')
print(size)

如何使用跨平台 KIVY API 制作上面的代码片段或类似的东西?

我查看了kivy metrics (https://kivy.org/doc/stable/api-kivy.metrics.html) and core.text docs (https://kivy.org/doc/stable/api-kivy.core.text.html),里面有相关的方法,但是找不到我需要的。

根据@johnAnderson 的以下评论,我尝试了以下操作,但出现分段错误:

from kivy.core.text import Label as CoreLabel

my_label = CoreLabel()
my_label.text = 'hello'
my_label.refresh()
hello_texture = my_label.texture
print(hello_texture.text_size())

如有任何指点,我们将不胜感激。谢谢

这个有用吗:

AdaptiveLabel = Label(
    size_hint_x = None,
    text = "Custom text",
    font_size = custom_size,
    )
AdaptiveLabel.texture_update()
AdaptiveLabel.width = AdaptiveLabel.texture_size[0]
# And then,
print(AdaptiveLabel.size)

谢谢大家。 @JohnAnderson 和@ApuCoder,让我走上了正确的道路。 通过 kivy.core.text 文档,我发现了以下方法来做我想要的事情:

from kivy.core.text import Label as CoreLabel
string = 'Hello world'
my_label = CoreLabel(
    font_size=12,
)
print(f'{my_label.get_extents(string)=}')

以上(使用get_extents(str)方法)return与@ApuCoder建议的方法结果相同,但不需要实例化kivy标签。 @ApuCoder建议的方法(稍作修改)是:

from kivy.uix.label import Label
string = 'Hello world'
AdaptiveLabel = Label(
    text=string,
    font_size=12,
    )
AdaptiveLabel.texture_update()
AdaptiveLabel.width = AdaptiveLabel.texture_size[0]
print(f'{AdaptiveLabel.texture_size=}')

两个return:

my_label.get_extents(string)=(61, 15)
AdaptiveLabel.texture_size=[61, 15]

注意,如果我不初始化 font_size,CoreLabel 的默认值为 12,但 kivy.uix.Label 的默认值为 15。

最后的片段:

import kivy.core.text
def get_str_pixel_width(string: str, **kwargs) -> int:
    return kivy.core.text.Label(**kwargs).get_extents(string)[0]

谢谢大家,希望对你有帮助。