如何使用KIVY API计算特定字体和大小的字符串长度(以像素为单位)? [英] How to calculate the length of a string in pixels for specific font and size, using KIVY API?

查看:0
本文介绍了如何使用KIVY API计算特定字体和大小的字符串长度(以像素为单位)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我发现了一个类似的问题,How to calculate length of string in pixels for specific font and size?有一个使用PIL的解决方案,但我无法解决:

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

如何使用跨平台KIVY API使上面的代码段或类似的内容工作?

我查看了kivy指标(https://kivy.org/doc/stable/api-kivy.metrics.html)和core.text文档(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())

如有任何提示,我们将不胜感激。谢谢

推荐答案

谢谢大家。@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)方法)返回的结果与@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=}')

同时返回:

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]

谢谢大家,希望这能有所帮助。

这篇关于如何使用KIVY API计算特定字体和大小的字符串长度(以像素为单位)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆