找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 92|回复: 0

[原创] 【功能组件】自适应尺寸文本

[复制链接]
发表于 7 小时前 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
出于美术需求写的一个组件
功能是根据xysize或容器xysize的约束自适应文本字号。
典型情况:
    ·多语言的时候,中文只有几个字,外语却一大串。
    ·同一个区域,填充不同长度的文本时候,不希望影响布局。
[RenPy] 纯文本查看 复制代码
# ---------- 自动缩放字体的文本组件 ----------
python early:
    """
    Author: Maz
    License: MIT
    """
    class AutoSizeText(renpy.Displayable):
        def __init__(self, text, **kwargs):
            super(AutoSizeText, self).__init__(**kwargs)
            self._text = text
            self._properties = kwargs
            self._properties['layout'] = "nobreak"

        def render(self, width, height, st, at):
            tw = width if (width and width > 0) else None
            th = height if (height and height > 0) else None

            # 没有尺寸约束,直接用原始字号
            if tw is None and th is None:
                t = Text(self._text, **self._properties)
                return t.render(width, height, st, at)

            # 从 style 系统取原始字号和宽高尺寸
            temp_text = Text(self._text, **self._properties)
            base_size = temp_text.style.size
            mw, mh = temp_text.size(width=tw or 4096, height=th or 4096)

            # 计算宽高的缩放比,取最小尺寸
            ratio = 1.0
            if tw and mw > tw:
                ratio = min(ratio, tw / mw)
            if th and mh > th:
                ratio = min(ratio, th / mh)
            
            # 用适用字号构建 Text
            if ratio < 1.0:
                new_size = max(int(base_size * ratio), 1)
            else:
                new_size = base_size
            self._properties['size'] = new_size
            result = Text(self._text, **self._properties)
            return result.render(width, height, st, at)

    # 注册 SL 语句
    # 关键字autosize接收0个子组件、传给位置参数text、打包关键字参数传给renpy预定义的组,也就是文本特性、位置特性
    renpy.register_sl_statement("autosize",children=0)\
        .add_positional("text")\
        .add_property_group("text")\
        .add_property_group("position")

# 配套 screen
screen autosize(text,**properties):
    add AutoSizeText(text,**properties)

使用方法和Text()组件完全一致,快捷语法则使用关键字autosize
[RenPy] 纯文本查看 复制代码
screen texttest():
    hbox:
        xsize 600
        align (0.5, 0.5)
        frame:
            autosize "这是一段很长的测试文字,它会自动缩小以适应宽度" color "#fff" size 48



您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|RenPy中文空间 ( 苏ICP备17067825号 )

GMT+8, 2026-7-29 19:58 , Processed in 0.016117 second(s), 6 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表