Skip to content
Hokusai2.2.2
ivantokar.com

Generated text

Hokusai renders text with libvips and Pango. Hokusai.text(_:layout:style:) returns an ordinary immutable pipeline (a transparent image of the text) that you can transform, composite or encode on its own; drawText is sugar for compositing that pipeline onto an existing one. Text rendering needs a libvips built with Pango (Hokusai.capabilities().textRendering), and a build without it reports HokusaiError.unsupported from the terminal, not from the call.

TextLayout sets the size of the text box:

  • .natural (default): as large as the text needs; lines break only at newlines.
  • .width(_:wrap:): wrap lines to a pixel width at the style’s font size and DPI. wrap is .word (default), .character, .wordCharacter (word breaks, plus breaks inside a word too long for a line) or .none.
  • .fit(width:height:): the largest resolution at which the text fits the box. The style’s dpi is not used and lineHeight must stay 1.
let style = TextStyle(fontSize: 40, color: Color(red: 0.1, green: 0.14, blue: 0.3))
let sentence: TextContent = "The lighthouse keeper wound the clock every evening."
// natural: as large as the text needs; lines break only at newlines.
let natural = try Hokusai.text(sentence, style: style)
// width: wrap lines to a pixel width.
let wrapped = try Hokusai.text(sentence, layout: .width(420), style: style)
// width with .character breaks anywhere, `.none` never breaks and clips at the width.
let clipped = try Hokusai.text(sentence, layout: .width(420, wrap: .none), style: style)
// fit: the largest size that fits the box (the style's dpi is not used).
let fitted = try Hokusai.text(sentence, layout: .fit(width: 420, height: 120), style: style)
for (name, text) in [("natural", natural), ("wrapped", wrapped), ("clipped", clipped), ("fitted", fitted)] {
try await text.png().write(to: URL(fileURLWithPath: "\(name).png"))
}
  • The sentence on one long line, 954 by 38 pixels.
    .naturalPNG · 954 × 38 · 8 KB
  • The sentence wrapped into three lines, 393 by 120 pixels.
    .width(420)PNG · 393 × 120 · 11 KB
  • The sentence on one line again; no wrapping happened.
    .width(420, wrap: .none)PNG · 954 × 38 · 8 KB
  • The sentence fitted into a 420 by 120 box, three lines, 393 by 120 pixels.
    .fit(420 × 120)PNG · 393 × 120 · 11 KB

The measured sizes are in each caption. Note that .width(420) produced a 393-pixel-wide image because the lines broke before reaching the limit, and that wrap: .none behaved like .natural (954 × 38) in this build, so do not rely on it to clip text; clip with extract if you need that.

Property Type Default Bounds
font String "sans" Pango family and style without size, e.g. "Helvetica Bold"; not a file path.
fontFile URL? nil A local TTF or OTF file made available to font for this render. Needs libvips with fontconfig; a file libvips cannot load is only a warning and the named font is used.
fontSize Int 24 1…2000 points at dpi.
color Color black
alignment TextAlignment .left .left, .center, .right.
justify Bool false Stretches wrapped lines to the full width.
lineHeight Double 1 0.5…5, multiple of the font’s natural line height.
dpi Int 72 1…2400; ignored by .fit.
stroke TextStroke? nil Outline: color, width in (0, 64].
shadow TextShadow? nil offsetX/offsetY within ±10,000, blur 0…64 (default 1.2), color (its opacity is the shadow’s).
rotation Double 0 Clockwise degrees; finite.
let base = TextStyle(font: "sans Bold", fontSize: 72, color: Color(red: 0.1, green: 0.14, blue: 0.3))
var stroked = base
stroked.color = .white
stroked.stroke = TextStroke(color: Color(red: 0.1, green: 0.14, blue: 0.3), width: 4)
var shadowed = base
shadowed.shadow = TextShadow(offsetX: 4, offsetY: 4, blur: 3)
var rotated = base
rotated.rotation = -12
let variants: [(String, TextStyle)] = [("plain", base), ("stroke", stroked), ("shadow", shadowed), ("rotated", rotated)]
for (name, style) in variants {
try await Hokusai.text("Hokusai", style: style).png().write(to: URL(fileURLWithPath: "\(name).png"))
}
// Alignment and line height apply to multi-line text.
var centred = TextStyle(fontSize: 36, color: Color(red: 0.1, green: 0.14, blue: 0.3))
centred.alignment = .center
centred.lineHeight = 1.4
try await Hokusai.text("Hokusai\nSwift image processing", style: centred).png()
.write(to: URL(fileURLWithPath: "centred.png"))
  • The word Hokusai in dark blue bold type.
    plainPNG · 270 × 55 · 4 KB
  • White letters with a dark blue outline.
    strokePNG · 278 × 63 · 9 KB
  • Dark blue letters with a soft drop shadow to the lower right.
    shadowPNG · 290 × 75 · 12 KB
  • The word tilted twelve degrees anticlockwise on a larger canvas.
    rotation −12PNG · 276 × 110 · 11 KB
  • Two centred lines: Hokusai above Swift image processing, with generous line spacing.
    centre, lineHeight 1.4PNG · 367 × 86 · 7 KB

Fonts come from the host: install what your application needs and use the installed family name. Package fonts with the app and load them with fontFile when the host cannot be controlled.

TextContent is .plain(String) or .markup(String); a string literal is plain. Plain text is always escaped, so any user string is safe to render. .markup is Pango markup (not HTML or CSS) for mixed fonts, sizes and colours; invalid markup fails when the text is rendered.

// Pango markup mixes fonts, sizes and colours in one text. (Plain text is always escaped.)
let markup = """
<span size="xx-large" weight="bold">Sale</span> <span foreground="#c83030">−30%</span>
<i>this week only</i> · <span font_family="monospace">code HOKUSAI</span>
"""
try await Hokusai.text(.markup(markup), style: TextStyle(fontSize: 36, color: Color(red: 0.1, green: 0.14, blue: 0.3)))
.png().write(to: URL(fileURLWithPath: "markup.png"))
// Characters that look like markup are safe in plain text.
try await Hokusai.text(.plain("a < b & c"), style: TextStyle(fontSize: 36, color: Color(red: 0.1, green: 0.14, blue: 0.3)))
.png().write(to: URL(fileURLWithPath: "plain-escaped.png"))
  • Sale in large bold, minus 30 percent in red, then italic and monospace text on a second line.
    markupPNG · 515 × 104 · 12 KB
  • The text a less-than b and c rendered literally.
    plain, escapedPNG · 142 × 27 · 2 KB

drawText(_:placement:layout:style:) composites the rendered text with the same placement, clipping and blending rules as any other layer (Composition). placement is .at(x:y:) or .gravity(_:offsetX:offsetY:).

let photo = try Hokusai(url: URL(fileURLWithPath: "scene.png")).resize(width: 640)
var style = TextStyle(font: "sans Bold", fontSize: 40, color: .white)
style.shadow = TextShadow(offsetX: 2, offsetY: 2, blur: 2, color: Color(red: 0, green: 0, blue: 0, opacity: 0.7))
try await photo
.drawText("Pharos Point", placement: .gravity(.southWest, offsetX: 24, offsetY: 20), style: style)
.webp(quality: 88)
.write(to: URL(fileURLWithPath: "caption.webp"))
  • The landscape with the white caption Pharos Point and a soft shadow in the lower left corner.
    drawTextWEBP · 640 × 400 · 15 KB
func attempt(_ name: String, _ build: () throws -> Hokusai) async {
do {
let output = try await build().png().data()
print(name, "→", output.info.width, "×", output.info.height)
} catch {
print(name, "→ throws", error)
}
}
let style = TextStyle(fontSize: 24)
await attempt("hello") { try Hokusai.text("Hello", style: style) }
await attempt("empty text") { try Hokusai.text("", style: style) }
await attempt("font file as family") { try Hokusai.text("Hi", style: TextStyle(font: "/fonts/Inter.ttf")) }
await attempt("fontSize 3000") { try Hokusai.text("Hi", style: TextStyle(fontSize: 3000)) }
await attempt("fit with lineHeight") {
var tall = TextStyle(); tall.lineHeight = 2
return try Hokusai.text("Hi", layout: .fit(width: 200, height: 100), style: tall)
}
await attempt("invalid markup") { try Hokusai.text(.markup("<b>unclosed"), style: style) }
Call Result
Hokusai.text("Hello", style: TextStyle(fontSize: 24)) a 52 × 19 image
empty text invalidOption(name: "text", …"must not be empty")
font that is a path (/fonts/Inter.ttf) invalidOption(name: "font", …"is a family name; pass a font file as fontFile")
fontSize: 3000 invalidOption: “must be from 1 through 2000”
.fit with lineHeight other than 1 invalidOption: “must be 1 with a fit layout”
invalid markup invalidInput: “the text is not valid Pango markup”