6

如果我想编写一个以 PDF 格式生成矢量图形的 Python 脚本,那么适合这项工作的工具是什么?特别是,我需要绘制带有圆角的填充多边形(即由直线和圆弧组成的平面图形)。

似乎matplotlib使得绘制圆角矩形和尖角一般多边形变得相当容易。但是,要绘制圆角的多边形,似乎我必须首先计算一个近似形状的贝塞尔曲线。

有没有更直接的方法?或者是否有另一个库可以用来计算近似于我想要生成的形状的贝塞尔曲线?理想情况下,我会简单地为每个顶点指定(位置,角半径)对。

这是一个示例:我想指定红色多边形(+每个角的半径),库将输出灰色图形:

例子

(对于凸多边形,我可以作弊并使用粗笔绘制多边形的轮廓。但是,这在非凸的情况下不起作用。)

4

2 回答 2

14

这是一个有点老套的 matplotlib 解决方案。主要的复杂性与使用 matplotlibPath对象构建复合材料有关Path

#!/usr/bin/env python

import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch, Polygon
from matplotlib.transforms import Bbox, BboxTransformTo

def side(a, b, c):
    "On which side of line a-b is point c? Returns -1, 0, or 1."
    return np.sign(np.linalg.det(np.c_[[a,b,c],[1,1,1]]))

def center((prev, curr, next), radius):
    "Find center of arc approximating corner at curr."
    p0, p1 = prev
    c0, c1 = curr
    n0, n1 = next
    dp = radius * np.hypot(c1 - p1, c0 - p0)
    dn = radius * np.hypot(c1 - n1, c0 - n0)
    p = p1 * c0 - p0 * c1
    n = n1 * c0 - n0 * c1
    results = \
        np.linalg.solve([[p1 - c1, c0 - p0],
                         [n1 - c1, c0 - n0]],
                        [[p - dp, p - dp, p + dp, p + dp],
                         [n - dn, n + dn, n - dn, n + dn]])
    side_n = side(prev, curr, next)
    side_p = side(next, curr, prev)
    for r in results.T:
        if (side(prev, curr, r), side(next, curr, r)) == (side_n, side_p):
            return r
    raise ValueError, "Cannot find solution"

def proj((prev, curr, next), center):
    "Project center onto lines prev-curr and next-curr."
    p0, p1 = prev = np.asarray(prev)
    c0, c1 = curr = np.asarray(curr)
    n0, n1 = next = np.asarray(next)
    pc = curr - prev
    nc = curr - next
    pc2 = np.dot(pc, pc)
    nc2 = np.dot(nc, nc)
    return (prev + np.dot(center - prev, pc)/pc2 * pc,
            next + np.dot(center - next, nc)/nc2 * nc)

def rad2deg(angle):
    return angle * 180.0 / np.pi

def angle(center, point):
    x, y = np.asarray(point) - np.asarray(center)
    return np.arctan2(y, x)

def arc_path(center, start, end):
    "Return a Path for an arc from start to end around center."
    # matplotlib arcs always go ccw so we may need to mirror
    mirror = side(center, start, end) < 0
    if mirror: 
        start *= [1, -1]
        center *= [1, -1]
        end *= [1, -1]
    return Path.arc(rad2deg(angle(center, start)),
                    rad2deg(angle(center, end))), \
           mirror

def path(vertices, radii):
    "Return a Path for a closed rounded polygon."
    if np.isscalar(radii):
        radii = np.repeat(radii, len(vertices))
    else:
        radii = np.asarray(radii)
    pv = []
    pc = []
    first = True
    for i in range(len(vertices)):
        if i == 0:
            seg = (vertices[-1], vertices[0], vertices[1])
        elif i == len(vertices) - 1:
            seg = (vertices[-2], vertices[-1], vertices[0])
        else:
            seg = vertices[i-1:i+2]
        r = radii[i]
        c = center(seg, r)
        a, b = proj(seg, c)
        arc, mirror = arc_path(c, a, b)
        m = [1,1] if not mirror else [1,-1]
        bb = Bbox([c, c + (r, r)])
        iter = arc.iter_segments(BboxTransformTo(bb))
        for v, c in iter:
            if c == Path.CURVE4:
                pv.extend([m * v[0:2], m * v[2:4], m * v[4:6]])
                pc.extend([c, c, c])
            elif c == Path.MOVETO:
                pv.append(m * v)
                if first:
                    pc.append(Path.MOVETO)
                    first = False
                else:
                    pc.append(Path.LINETO)
    pv.append([0,0])
    pc.append(Path.CLOSEPOLY)

    return Path(pv, pc)

if __name__ == '__main__':
    from matplotlib import pyplot
    fig = pyplot.figure()
    ax = fig.add_subplot(111)
    vertices = [[3,0], [5,2], [10,0], [6,9], [6,5], [3, 5], [0,2]]

    patch = Polygon(vertices, edgecolor='red', facecolor='None',
                    linewidth=1)
    ax.add_patch(patch)

    patch = PathPatch(path(vertices, 0.5), 
                      edgecolor='black', facecolor='blue', alpha=0.4,
                      linewidth=2)
    ax.add_patch(patch)

    ax.set_xlim(-1, 11)
    ax.set_ylim(-1, 9)
    fig.savefig('foo.pdf')

上面脚本的输出

于 2011-10-09T19:10:47.700 回答
5

至于生成 PDF 文件,我建议看一下cairo库,这是一个支持“绘图”到 PDF 表面的矢量图形库。它也有 Python 绑定。

至于绘制带圆角的多边形,我不知道有什么图形库支持这个开箱即用。

但是在给定角半径的情况下计算多边形角处的弧坐标应该不会太复杂。基本上,您必须找到两个相邻边缘的角平分线上的点,该点与两个边缘都有距离r(即所需的半径)。这是圆弧的中心,为了找到起点和终点,您将从该点投影到两条边。

可能有不平凡的情况,例如,如果多边形边缘太短而无法容纳两条弧线(我想在这种情况下您必须选择较小的半径),可能还有其他情况,我目前不知道该怎么办的 ...

高温高压

于 2011-10-09T10:52:01.247 回答