Search Docs
Loading...
Skip to content

Customize Fonts

Register custom typefaces with the CE.SDK engine, apply them to text blocks, keep the requested font identity and check how the text renders.

6 mins
estimated time

CE.SDK renders text with fonts from typeface definitions. You can apply a typeface to a text block directly, register typefaces in an asset source so that the engine resolves font requests, or supply your own font provider. This guide uses only the engine API.

Typeface and Font Structure#

A Typeface represents a font family. It has a name and a fonts array that lists each font variant the engine can apply.

Each Font carries:

  • uri: URL of the font file (TTF, OTF, WOFF or WOFF2)
  • subFamily: Human-readable variant name, such as "Regular" or "Bold Italic"
  • weight: A FontWeight case: .thin, .extraLight, .light, .normal, .medium, .semiBold, .bold, .extraBold or .heavy
  • style: A FontStyle case: .normal or .italic
let orbitron = Typeface(
name: "Orbitron",
fonts: [
Font(
uri: URL(
string: "https://fonts.gstatic.com/s/orbitron/v35/yMJMMIlzdpvBhQQL_SC3X9yhF25-T1nyGy6xpg.ttf",
)!,
subFamily: "Regular",
weight: .normal,
style: .normal,
),
Font(
uri: URL(
string: "https://fonts.gstatic.com/s/orbitron/v35/yMJMMIlzdpvBhQQL_SC3X9yhF25-T1ny_Cmxpg.ttf",
)!,
subFamily: "Bold",
weight: .bold,
style: .normal,
),
],
)

The example loads Orbitron from a public CDN. In production, point uri at assets you control.

Register a Typeface Source#

Register typefaces as assets so that the engine can resolve font requests without an application provider. The example reads the asset base URL from the engine settings and loads the default typeface content from it with engine.asset.addLocalAssetSourceFromJSON(_:). The call returns the ID of the source that the JSON declares.

let basePath = try engine.editor.getSettingString("basePath")
guard let baseURL = URL(string: basePath) else { return }
let typefaceSourceID = try await engine.asset.addLocalAssetSourceFromJSON(
baseURL
.appendingPathComponent("ly.img.typeface")
.appendingPathComponent("content.json"),
)

Add your typeface to that source with engine.asset.addAsset(to:asset:). Each AssetDefinition wraps the typeface in an AssetPayload:

try engine.asset.addAsset(
to: typefaceSourceID,
asset: AssetDefinition(
id: "orbitron",
groups: ["latin"],
payload: AssetPayload(typeface: orbitron),
label: ["en": "Orbitron"],
),
)

To register only your own typefaces, skip the default content. Create an empty source with engine.asset.addLocalSource(sourceID:) and add your typefaces to it.

Apply Fonts Programmatically#

Two APIs apply typefaces to text blocks directly:

  • engine.block.setFont(_:fontFileURL:typeface:) swaps the font for the entire block and resets per-range formatting.
  • engine.block.setTypeface(_:typeface:in:) applies the typeface to a range and preserves existing formatting.
static func applyTypeface(engine: Engine, textBlock: DesignBlockID, typeface: Typeface) throws {
try engine.block.setFont(
textBlock,
fontFileURL: typeface.fonts[0].uri,
typeface: typeface,
)
}

Query the current typefaces with engine.block.getTypeface(_:) (the block’s base typeface) or engine.block.getTypefaces(_:in:) (the unique typefaces inside a range). The Text Styling guide covers font sizes, weights, styles, colors and decorations.

Saved Content and Reader Compatibility#

The first concrete typeface definition for a family keeps the family name as its asset ID. If another definition uses that name with different font files or cuts, the engine saves it under a separate ID. Font requests also use their own identity keys. This applies to scenes, archives and saved blocks.

text/typeface can hold an ID that is not the family name. Read the name with block.getTypeface(id).name.

Earlier engines can render text from its stored font files, but cannot read a typeface or change its weight and style when the saved ID differs from the family name. Content with one concrete definition per family and no font requests stays editable in earlier engines.

Upgrade engines that must edit content with these separate identities. The updated reader still accepts older content. Keep original files before re-saving content that older applications must continue to edit.

Change the Fonts of a Registered Typeface#

When a font family changes, register its typeface again in your local asset source: remove the old asset, then add one with the current fonts. A typeface counts as registered again when it has the same name and at least one of the same font files.

A weight or style that the new typeface no longer has stays in the scene while text uses it, so that text keeps its look. Once no text uses it, the scene drops it, the font style menu stops offering it, and saved scenes no longer store it. To move text off a removed weight, set an available weight or style on that text.

A typeface with the same name but other font files, such as one that a template brings, keeps all its fonts.

Preserve Requested Font Identity#

The example installs a provider that returns its known typeface and font. It stores a request for the registered asset, waits for the font resources and reads the request back. When the function returns, it restores registered-source resolution.

@MainActor
private static func applyStoredFontRequest(
engine: Engine,
textBlock: DesignBlockID,
typeface: Typeface,
font: IMGLYEngine.Font,
sourceID: String,
) async throws {
try engine.editor.setTypefaceResolver { request in
request.family == typeface.name ? FontResolverResult(typeface: typeface, font: font) : nil
}
defer { try? engine.editor.setTypefaceResolver(nil) }
let request = FontRequest(
family: typeface.name,
subFamily: font.subFamily,
weight: font.weight,
style: font.style,
assetSourceID: sourceID,
assetID: "orbitron",
)
try engine.block.setFontRequest(textBlock, request: request)
try await engine.block.forceLoadResources([textBlock])
print("Stored requests: \(try engine.block.getFontRequests(textBlock))")
}

A font request preserves the intended family, cut, weight, style and optional asset identity through scene and archive round trips, even when that font is unavailable. setFontRequest() stores this identity and starts asynchronous resolution. getFontRequests() returns the unique stored requests in source order, rather than the fonts currently used for rendering.

The request fields below use TypeScript names. Swift uses assetSourceID and assetID for the asset identifiers.

Field Purpose and default
family Required, nonempty family name.
subFamily Optional cut name; defaults to an empty string.
weight Requested weight; defaults to normal.
style Requested style; defaults to normal.
postScriptName Optional exact identity checked against the loaded font’s PostScript name.
assetSourceId Optional source identifier that limits asset lookup.
assetId Optional asset identifier within that source; requires assetSourceId.

Returned requests include the default subfamily, weight and style. Supplied optional identifiers must be nonempty.

Calling the setter without a range replaces the request for the whole block, even when text is selected. Calling the getter without a range reads the current selection, or the whole text when there is no selection. Explicit ranges follow the platform’s editable-text convention. These ranges can differ from the rendered UTF-16 ranges returned by diagnostics after case conversion or template substitution.

By default, the engine searches registered local asset sources for matching typeface definitions, reading at most 100 pages of each source. Identical requests share a pending lookup. Other sources are queried only when the request names an assetSourceId; an assetId selects one asset directly. To retry unresolved requests after registering a source, call editor.setTypefaceResolver() again. Applications with an external font catalog can also install editor.setTypefaceResolver(). The provider returns the concrete typeface and chosen font, or no result when unavailable. Configure it on each engine before loading a scene that needs it; the callback itself is not saved in the scene.

When the provider returns no result, throws or rejects, the engine uses the default font, and the request reports substituted. It reports unresolved only when the default font cannot load either. Replacing the provider starts resolution again; completions from replaced providers, superseded requests or disposed engines are ignored. Removing the provider restores registered-source resolution.

Await block.forceLoadResources() when subsequent work needs settled font resources. A new request or provider replacement can move a ready text block back to pending. Block-state subscriptions let your application observe readiness changes; read the current state when notified. Resource failure rejects the resource-loading call and can still leave a fallback layout to inspect.

getTextRenderDiagnostics() retains the stored request alongside the actual loaded font and effective size. A fallback does not replace the stored identity, and substitution can change line breaks and dimensions. A resolved request alone does not guarantee that every glyph is present.

Existing setFont() and setTypeface() calls continue to apply concrete font choices and clear requests for the affected text. Use them when you already have the concrete definition. Use a font request when the design should retain its intended identity while availability changes.

Inspect Rendered Text#

Call engine.block.getTextRenderDiagnostics(_:) to check which fonts shaped the returned text, identify missing glyphs and inspect layout. The example waits for resources with forceLoadResources(_:) before it reads the snapshot and prints the result to the console.

@MainActor
private static func inspectTextRendering(engine: Engine, textBlock: DesignBlockID) async throws {
// Wait for font resources when the application needs a settled snapshot.
try await engine.block.forceLoadResources([textBlock])
let diagnostics = try engine.block.getTextRenderDiagnostics(textBlock)
print("Rendered text: \(diagnostics.fontUsage.text); state: \(diagnostics.fontUsage.state)")
for run in diagnostics.fontUsage.runs {
print("[\(run.from), \(run.to)): \(run.requestedFontFileURI) -> \(run.actualFontFileURI ?? "unresolved"); " +
"\(run.status); effective font size: \(run.effectiveFontSize)")
}
print("Missing glyph ranges: \(diagnostics.missingGlyphRanges)")
if let layout = diagnostics.layout {
print("Lines: \(layout.visibleLineCount)/\(layout.totalLineCount) visible, " +
"\(layout.clippedLineCount) clipped; required height: \(layout.requiredHeight); " +
"font scale: \(layout.fontScale); overshoot: \(layout.overshoot)")
}
}

The call updates pending layout and returns a snapshot without waiting for font downloads. Call it again after resources finish loading.

fontUsage contains the rendered text, its block state, and font runs. Each run names the requested font file and the loaded font file, when available.

Run status Meaning
resolved The requested font loaded for the run.
substituted A different font loaded, including fallback or emoji fonts.
unresolved No usable font loaded for the run.

Each run’s effectiveFontSize reports the shaped size in the scene’s font unit. It includes automatic fitting and superscript or subscript scaling.

The block state separately reports resource loading or failure. A failed font can produce a current fallback layout. Pending resources produce no runs or layout. If no current shape exists after a loading failure, the snapshot omits stale text and measurements.

A resolved run does not guarantee that every glyph is available. These diagnostics describe shaped text; they do not confirm that a frame was drawn or exported.

All ranges use half-open UTF-16 offsets into fontUsage.text, after case conversion and template substitution. Font runs return from and exclusive to values on every platform. Missing-glyph ranges use the same endpoints; Swift represents these ranges as Range<Int>. These offsets can differ from offsets used to edit the original text.

missingGlyphRanges identifies glyphs that remain missing after fallback. Ignored controls and trailing whitespace do not count as missing glyphs. This field remains available for curved text.

When present, layout contains:

  • totalLineCount: All laid-out lines, including hidden lines.
  • visibleLineCount: Lines visible with the block’s clipping configuration, independent of temporary editing visibility.
  • clippedLineCount: Lines hidden by that clipping configuration.
  • requiredHeight: The full Auto-height result at the current effective sizes, even when no line fits the frame.
  • fontScale: The common automatic fitting scale applied to authored font sizes.
  • overshoot: Nonnegative distances that glyph ink extends beyond the frame’s left, top, right, and bottom edges.

requiredHeight and overshoot use local scene design units before block transformations, stroke, effects, or animations. Overshoot includes ink on hidden lines. Intentional glyph overhang can produce nonzero overshoot; choose limits that suit your design.

Curved text omits planar layout measurements. An absent layout means those measurements are unavailable; it does not mean the text passed verification.

Troubleshooting#

Request Remains Unresolved#

  • Check the family, source and asset identifiers of the request.
  • Confirm that the provider returns a matching typeface and a readable font file.

Font Not Loading#

  • Confirm that the Font.uri is reachable from the app. CE.SDK fetches the font file from the URL you provide, so it must resolve over the network or point at a bundled file:// URL.
  • For HTTPS URLs, confirm that the app’s App Transport Security configuration does not block the host.
  • A sandboxed app needs the Outgoing Connections (Client) capability, com.apple.security.network.client, to download fonts.

getTypeface(_:) Throws#

A new .text block does not have an explicit typeface until setFont(_:fontFileURL:typeface:) is called once. Read with engine.block.getTypefaces(_:in:), which returns an empty array for the unset state, or apply a typeface first.

API Reference#

Methods#

Method Description
engine.asset.addLocalAssetSourceFromJSON(_:) Load asset content from a JSON URL into the source declared by the JSON. Use ly.img.typeface/content.json under the asset base URL to register the default typefaces.
engine.asset.addLocalSource(sourceID:) Register an empty local asset source.
engine.asset.addAsset(to:asset:) Add an AssetDefinition to a registered source.
engine.block.setFont(_:fontFileURL:typeface:) Apply a font to the entire text block. Resets per-range formatting.
engine.block.setTypeface(_:typeface:in:) Apply a typeface to a text range. Preserves existing formatting.
engine.block.getTypeface(_:) Return the base typeface of a text block.
engine.block.getTypefaces(_:in:) Return the unique typefaces inside a text range.
engine.block.setFontRequest(_:request:in:) Store font identity for later resolution.
engine.block.getFontRequests(_:in:) Read unique stored font requests.
engine.editor.setTypefaceResolver(_:) Supply an application font provider or restore registered-source resolution.
engine.block.getTextRenderDiagnostics(_:) Inspect rendered font runs, effective font sizes, missing glyphs and planar layout.
engine.block.forceLoadResources(_:) Wait for the text block’s font resources before reading a settled snapshot.

Types#

Type Description
Typeface A font family: name plus an array of Font variants.
Font A single font variant: uri, subFamily, weight and style.
AssetDefinition An asset entry to register with a source. Carries an optional payload and label.
AssetPayload Container for structured asset data; pass a Typeface via payload.typeface.
FontRequest A stored font identity: family, subFamily, weight, style and the optional postScriptName, assetSourceID and assetID.
FontResolverResult The typeface and the chosen font that a provider returns for a request.

Next Steps#

  • Text Styling: Programmatic text styling APIs, including font weight, style, color and decorations
  • Add Text: Create text blocks and set their initial content
  • Text Decorations: Underline, strikethrough and overline decorations on text