生成 PDF 文件,绘制圆角多边形
如果我想编写一个生成PDF 格式矢量图形的 Python 脚本,那么什么工具适合这项工作?特别是,我需要绘制带有圆角的填充多边形(即由直线和圆弧组成的平面图形)。
似乎 matplotlib 使得绘制带圆角的矩形和带尖角的一般多边形相当容易。然而,要绘制带有圆角的多边形,似乎我必须首先计算近似形状的贝塞尔曲线。
有没有更简单的方法可以利用?或者是否有另一个库可以用来计算近似于我想要生成的形状的贝塞尔曲线?理想情况下,我只需为每个顶点指定(位置,角半径)对。
这是一个示例:我想指定红色多边形(+每个角的半径),并且库将输出灰色图形:
(对于凸多边形,我可以作弊并使用粗笔绘制多边形的轮廓。但是,这在非凸情况下不起作用。)
What's the right tool for the job if I want to write a Python script that produces vector graphics in PDF format? In particular, I need to draw filled polygons with rounded corners (i.e., plane figures that are composed of straight lines and circular arcs).
It seems that matplotlib makes it fairly easy to draw rectangles with rounded corners and general polygons with sharp corners. However, to draw polygons with rounded corners, it seems that I have to first compute a Bézier curve that approximates the shape.
Is there anything more straightforward available? Or is there another library that I can use to compute the Bézier curve that approximates the shape that I want to produce? Ideally, I would simply specify the (location, corner radius) pair for each vertex.
Here is an example: I would like to specify the red polygon (+ the radius of each corner) and the library would output the grey figure:
(For convex polygons I could cheat and use a thick pen to draw the outline of the polygon. However, this does not work in the non-convex case.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个有点 hacky matplotlib 解决方案。主要的复杂性与使用 matplotlib Path 对象构建复合 Path 相关。
Here's a somewhat hacky matplotlib solution. The main complications are related to using matplotlib
Path
objects to build a compositePath
.至于生成PDF文件,我建议看看 cairo 库,这是一个支持“绘图”的矢量图形库” 到 PDF 表面。它也有 Python 绑定。
至于绘制带有圆角的多边形,我不知道有任何图形库支持开箱即用。
但在给定角半径的情况下计算多边形角处的圆弧坐标应该不会太复杂。基本上,您必须找到两个相邻边的角平分线上的点,该点与两条边的距离为r(即所需的半径)。这是圆弧的中心,为了找到起点和终点,您将从该点投影到两条边。
可能存在一些不平凡的情况,例如,如果多边形边缘太短而无法容纳两个圆弧(我想在这种情况下您必须选择较小的半径),该怎么办,也许还有其他情况,我目前不知道的...
HTH
As for producing PDF files, I would suggest to have a look at the cairo library, a vector graphics libaray which support "drawing" into PDF surfaces. It has Python bindings too.
As for drawing polygons with rounded corners, I'm not aware of any graphics library which supports this out of the box.
But it shouldn't be too complicated to compute the arc coordinates at polygon corners given the corner radius. Basically you have to find the point on the angle bisector of two adjacent edges which has the distance
r
(i.e. the desired radius) from both edges. This is the center of the arc, for finding the starting and ending point, you'll project from this point to the two edges.There might be non-trivial cases, e.g. what to do, if polygon edges are too short to fit two arcs (I guess you'll have to select a smaller radius in this case), and maybe others, I'm currently not aware of ...
HTH