0

我有一个字幕对象,有时会使用 Matplotlib 的内置包装功能进行包装。但是,当试图获取字幕的高度时,我似乎总是得到与一行相对应的高度。我哪里错了?这就是我正在尝试的:

from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

fig = Figure((4, 4))
FigureCanvas(fig)

text_1 = "I'm a short text"
text_2 = "I'm a longer text that will be wrapped autoamtically by Matplotlib, using wrap=True"

title = fig.suptitle(text_1, wrap=True)
fig.canvas.draw()  # Draw text to find out how big it is
bbox = title.get_window_extent()
print(bbox.width)  # 105
print(bbox.height)  # 14

title = fig.suptitle(text_2, wrap=True)
fig.canvas.draw()  # Draw text to find out how big it is
bbox = title.get_window_extent()
print(bbox.width)  # 585 <-- This looks about right
print(bbox.height)  # Still 14 even though this time the text is wrapped!

对象也会发生同样的事情Text(使用类似fig.text(0.5, 0.5, text_1, wrap=True).

4

1 回答 1

0

感谢@ImportanceOfBeingErnest指出这是不可能的。这是一种解决方法,通过检查文本被分解成的行数并乘以近似的行高来实现。这在自动插入的中断与手动混合(即"\n"文本中有一个)时有效,但会偏离多个像素。欢迎任何更准确的建议。

def get_text_height(fig, obj):
    """ Get the approximate height of a text object.
    """
    fig.canvas.draw()  # Draw text to find out how big it is
    t = obj.get_text()
    r = fig.canvas.renderer
    w, h, d = r.get_text_width_height_descent(t, obj._fontproperties,
                                              ismath=obj.is_math_text(t))
    num_lines = len(obj._get_wrapped_text().split("\n"))
    return (h * num_lines)

text = "I'm a long text that will be wrapped automatically by Matplotlib, using wrap=True"
obj = fig.suptitle(text, wrap=True)
height = get_text_height(fig, obj)
print(height)  # 28 <-- Close enough! (In reality 30)
于 2018-06-07T15:22:11.647 回答