一、Cairo 简介
Cairo 是一个2D矢量图形库,支持多种输出设备(如PNG、PDF、SVG、窗口系统)。PyCairo 是 Cairo 的 Python 绑定,允许通过 Python 代码实现高质量的图形绘制。
二、安装 PyCairo
# 通过 pip 安装(注意包名可能是 pycairo 或 cairo)
pip install pycairo
三、基础概念与核心类
-
Surface(表面)
表示绘图的目标介质(如内存、文件、窗口)。常见类型:ImageSurface
: 位图图像(如PNG)PDFSurface
: PDF 文件SVGSurface
: SVG 矢量图
-
Context(上下文)
控制绘图操作的核心对象,管理路径、颜色、变换等绘图状态。
四、基础绘图方法
示例1:绘制简单图形(PNG)
import cairo
# 1. 创建 Surface 和 Context
width, height = 400, 300
surface = cairo.ImageSurface(cairo.Format.ARGB32, width, height)
ctx = cairo.Context(surface)
# 2. 设置背景色
ctx.set_source_rgb(0.9, 0.9, 0.9) # RGB 范围 0~1
ctx.paint() # 填充整个表面
# 3. 绘制红色矩形
ctx.set_source_rgb(1, 0, 0) # 红色
ctx.rectangle(50, 50, 100, 80) # (x, y, width, height)
ctx.fill() # 填充形状
# 4. 绘制蓝色边框圆形
ctx.arc(250, 150, 40, 0, 2 * 3.14159) # (x, y, radius, start_angle, end_angle)
ctx.set_source_rgb(0, 0, 1) # 蓝色
ctx.set_line_width(3) # 线宽
ctx.stroke() # 描边路径
# 5. 保存为 PNG
surface.write_to_png("basic_shapes.png")
注释说明:
set_source_rgb()
: 设置绘图颜色(RGB值)。rectangle()
和arc()
: 定义路径形状。fill()
和stroke()
: 分别表示填充路径和绘制路径边框。write_to_png()
: 将结果保存为PNG文件。
五、高级特性
1. 坐标变换
# 平移、旋转、缩放示例
ctx.save() # 保存当前状态
ctx.translate(200, 150) # 移动原点至 (200,150)
ctx.rotate(0.25 * 3.14159) # 旋转45度(弧度制)
ctx.scale(2, 2) # 缩放2倍
ctx.rectangle(-20, -20, 40, 40) # 绘制正方形
ctx.set_source_rgb(0, 1, 0)
ctx.fill()
ctx.restore() # 恢复之前保存的状态
2. 渐变填充
# 线性渐变
linear = cairo.LinearGradient(0, 0, 300, 300)
linear.add_color_stop_rgba(0, 1, 0, 0, 1) # 起点红色
linear.add_color_stop_rgba(1, 0, 0, 1, 0.5) # 终点半透明蓝色
ctx.set_source(linear)
ctx.rectangle(50, 50, 200, 200)
ctx.fill()
3. 路径操作与曲线
# 绘制贝塞尔曲线
ctx.move_to(50, 200) # 起点
ctx.curve_to(100, 50, 200, 350, 350, 200) # 控制点1, 控制点2, 终点
ctx.set_source_rgb(0.5, 0, 0.5)
ctx.set_line_width(4)
ctx.stroke()
4. 文本渲染
# 设置字体并绘制文本
ctx.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
ctx.set_font_size(30)
ctx.move_to(50, 100)
ctx.set_source_rgb(0, 0, 0)
ctx.show_text("Hello Cairo!") # 绘制文本
六、综合案例:绘制复杂图形
import cairo
# 初始化
surface = cairo.ImageSurface(cairo.Format.ARGB32, 600, 400)
ctx = cairo.Context(surface)
ctx.set_source_rgb(1, 1, 1)
ctx.paint()
# 绘制渐变背景
gradient = cairo.RadialGradient(300, 200, 10, 300, 200, 300)
gradient.add_color_stop_rgba(0, 0.8, 0.8, 1, 1)
gradient.add_color_stop_rgba(1, 0.2, 0.2, 0.5, 1)
ctx.set_source(gradient)
ctx.rectangle(0, 0, 600, 400)
ctx.fill()
# 绘制旋转矩形
ctx.save()
ctx.translate(300, 200)
for i in range(12):
ctx.rotate(3.14159 / 6) # 每次旋转30度
ctx.set_source_rgba(0, 0.5, 0, 0.5)
ctx.rectangle(-30, -30, 60, 60)
ctx.fill()
ctx.restore()
# 保存结果
surface.write_to_png("advanced_demo.png")
七、关键注意事项
- 坐标系:原点
(0,0)
在左上角,x向右增长,y向下增长。 - 路径操作:所有路径需通过
fill()
或stroke()
才会生效。 - 状态堆栈:
save()
和restore()
用于管理绘图状态(如颜色、变换)。
通过结合基础方法和高级特性,Cairo 能实现复杂的矢量图形绘制。建议参考 Cairo官方文档 深入探索更多功能。