首页 > 解决方案 > 仿射变换后不同高度的字母

问题描述

我必须在不改变宽度的情况下绘制一个字符串并转换它的高度。我确实在这里找到了一个 Scale 课程。但是,我发现不同字母之间存在高度差异(见图:G,O,C高于T,H,A,并超过了下限)。

如何使所有字母的高度和开头完全相同y_axis

我尝试使用txt1.get_window_extent()来获取字符串bbox的坐标,但是仿射变换后bbox没有缩放(灰色矩形)。

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    import matplotlib.patheffects
    # import matplotlib.patches as patches

    #-----------------------------------------------------------

    class Scale(matplotlib.patheffects.RendererBase):
        def __init__(self, sx, sy = None):
            self._sx = sx
            self._sy = sy

        def draw_path(self, renderer, gc, tpath, affine, rgbFace):
            affine = affine.identity().scale(self._sx, self._sy) + affine
            renderer.draw_path(gc, tpath, affine, rgbFace)

    #-----------------------------------------------------------

    N=12
    fig = plt.figure(figsize = (N+1, 4))
    ax = fig.add_subplot(111)

    font = FontProperties()
    font.set_size(80)
    font.set_weight('bold')
    font.set_family('monospace')

    bbox_props = dict(boxstyle = "square, pad = 0.0", fill = 0, lw = 1, alpha = 0.5)

    ax.plot((0.0, 1.0), (0.1, 0.1), linestyle = '--') # dashed line
    ax.plot((0.0, 1.0), (0.9, 0.9), linestyle = '--')

    txt1 = ax.text(0.3, 0.1, 'GOTCHA', 
                    fontproperties = font,
                    ha = 'center',
                    va = 'baseline', 
                    bbox = bbox_props)
    txt2 = ax.text(0.8, 0.1, 'GOTCHA', 
                    fontproperties = font,
                    ha = 'center',
                    va = 'baseline',
                    color = 'blue', 
                    bbox = bbox_props)

    txt1.set_path_effects([Scale(1.0, 3.0)]) # 3X in height
    ax.set_ylim(0.0, 1.0)
    plt.savefig('test.png')

黑色“GOTCHA”是按比例缩放的

标签: pythonmatplotlibaffinetransform

解决方案


推荐阅读