生成PDF文件,绘制带有圆角的多边形 [英] Produce PDF files, draw polygons with rounded corners

查看:345
本文介绍了生成PDF文件,绘制带有圆角的多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

似乎 matplotlib 使得绘制带有圆角的矩形和带有尖角的常规多边形相当容易.但是,要绘制带有圆角的多边形,似乎我必须首先计算出近似于该形状的贝塞尔曲线.

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.)

推荐答案

对于生成PDF文件,我建议您看一下

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.

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

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

这篇关于生成PDF文件,绘制带有圆角的多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆