仿射变换后不同高度的字母

2024-05-23 16:11:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须绘制一个字符串并在不改变宽度的情况下变换它的高度。 我确实找到了一个Scale类here,它实现了这个技巧。但是,我发现不同字母之间的高度有差异(如图所示: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')

Black 'GOTCHA' is the scaled one


Tags: pathimportself高度matplotlibpltaxfont