Swift 的 2D 绘图库,支持多个后端,目前包括:
import PlatformGraphics
import Utils
// Create a new image and a graphics context
let ctx = try PlatformGraphicsContext(width: 300, height: 300)
// Draw some shapes
ctx.draw(line: LineSegment(fromX: 20, y: 20, toX: 50, y: 30))
ctx.draw(rect: Rectangle(fromX: 80, y: 90, width: 10, height: 40, color: Colors.yellow))
ctx.draw(text: Text("Test", at: Vec2(x: 0, y: 15)))
ctx.draw(ellipse: Ellipse(centerX: 150, y: 80, radius: 40))
ctx.draw(polygon: Polygon(points: [
Vec2(x: 210.0, y: 150.0),
Vec2(x: 100.0, y: 200.0),
Vec2(x: 170.0, y: 250.0)
], isFilled: false))
// Encode the image to a byte buffer
let image = try ctx.makeImage()
let data = try image.pngEncoded()
完整的示例可以在Snippets/DrawShapes.swift
中找到。 要运行它,请执行:
swift run DrawShapes Output/shapes.png
生成的 PNG 文件将被写入 Output/shapes.png
。
apt-get install libcairo2-dev
brew install cairo
swift build
swift test