Search Docs
Loading...
Skip to content

Customize Fonts

Load and configure custom fonts in CE.SDK to match brand guidelines or provide users with a curated font selection.

Editor with a text block rendering “Orbitron” in the custom typeface, and the font picker sheet open showing Orbitron listed alongside the bundled default typefaces with a checkmark indicating it is applied

6 mins
estimated time
GitHub

CE.SDK includes a set of default typefaces, but you can customize the available fonts by registering your own typeface assets. The editor’s font library reads from a single asset source whose ID is "ly.img.typeface" — anything registered under that ID, whether a single custom typeface or a full replacement of the bundled defaults, becomes the editor’s font picker.

This guide builds on GuideEditorConfiguration, a small helper class the iOS guides repository ships as a minimal baseline; substitute your own editor configuration class — the onCreate hook used here is available on every configuration. The Configuration guide covers how EditorConfiguration and EngineSettings set up the editor as a whole.

This guide covers how to:

  • Define typefaces with multiple font weights and styles
  • Add a custom typeface to the font library alongside the bundled defaults
  • Register an uploaded font file from its font info
  • Replace the defaults entirely
  • Apply fonts programmatically to text blocks

Typeface and Font Structure#

A Typeface represents a font family. It has a name shown in the editor’s font picker and a fonts array listing each individual font variant the editor can apply.

Each Font carries:

  • uri — URL of the font file (TTF, OTF, WOFF, or WOFF2)
  • subFamily — Human-readable variant name (e.g. "Regular", "Bold Italic")
  • weight — FontWeight: .thin, .extraLight, .light, .normal, .medium, .semiBold, .bold, .extraBold, or .heavy
  • style — FontStyle: .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.

Add a Custom Typeface to the Font Library#

The iOS editor’s font picker is hardcoded to read from a single asset source whose ID is "ly.img.typeface". Every typeface that shows up in the library — bundled or custom — must be registered under that ID. To add a custom typeface alongside the bundled defaults, load the bundled typeface content into that source first with engine.asset.addLocalAssetSourceFromJSON(_:), then add your own typeface to the same source with engine.asset.addAsset(to:asset:).

Read the asset base URL from the engine settings inside onCreate, then load the bundled typeface content:

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 custom typeface with engine.asset.addAsset(to:asset:), passing the source ID returned by the load call above. 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"],
),
)

The label dictionary controls how the asset appears in the editor’s font library.

Register an Uploaded Font#

When a user uploads a font file, you do not know its family name, weight or style in advance. engine.editor.getFontInfo(fontFileURI:) reads them from the file. It takes the URI of a TTF, OTF, WOFF or WOFF2 file as a string and returns a FontInfo.

Build the typeface asset from that info alone and add it to the typeface source:

static func addFontFile(engine: Engine, to sourceID: String, fontFileURL: URL) async throws {
let info = try await engine.editor.getFontInfo(fontFileURI: fontFileURL.absoluteString)
let typeface = Typeface(
name: info.family,
fonts: [
Font(uri: fontFileURL, subFamily: info.subFamily, weight: info.fontWeight, style: info.style),
],
)
try engine.asset.addAsset(
to: sourceID,
asset: AssetDefinition(
id: fontFileURL.absoluteString,
payload: AssetPayload(typeface: typeface),
label: ["en": info.family],
),
)
}
  • family is the typographic family name of the font. The example uses it as the typeface name and the asset label.
  • subFamily and style fill the Font entry directly.
  • fontWeight is the FontWeight value that is closest to the numeric weight of the file.
  • The example uses the font file URI as the asset ID, so each file gets its own asset.

The example calls this function in onCreate with the Codystar Regular file from Google Fonts.

For a variable font, isVariable is true and variationAxes lists each axis with its tag, minValue, defaultValue and maxValue. The other fields describe the default instance of the font. getFontInfo(fontFileURI:) throws an error with the code EDITOR.FONT_INFO_EXTRACT_FAILED when the file is not a font, and EDITOR.FONT_LOAD_FAILED when the URI is not reachable.

Replace the Default Typefaces#

To ship a custom-fonts-only library — no bundled defaults — skip the addLocalAssetSourceFromJSON(_:) call and register a fresh, empty local source under "ly.img.typeface" instead with engine.asset.addLocalSource(sourceID: "ly.img.typeface"). Then add typefaces to the empty source with engine.asset.addAsset(to: "ly.img.typeface", asset:). The font library shows only the typefaces you added.

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). For the full set of text-styling APIs — font sizes, weights, styles, colors, decorations — see the Text Styling guide.

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#

@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 reading 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#

Font Not Appearing in the Library#

  • Confirm the source is registered under ID "ly.img.typeface" — either by loading the bundled content with engine.asset.addLocalAssetSourceFromJSON(_:) or by creating an empty source with engine.asset.addLocalSource(sourceID: "ly.img.typeface"). The editor only reads from that exact ID.
  • Verify the asset’s payload is built with an AssetPayload(typeface:) value. A definition without a typeface payload is added to the source but the editor cannot render it as a font.

Font Not Loading#

  • Confirm the Font.uri is reachable from the device. CE.SDK fetches the font file at the URL you provide, so it must resolve over the network (or point at a bundled file:// URL).
  • For HTTPS URLs, confirm the host is not blocked by the app’s App Transport Security configuration.

Font Weight or Style Not Available#

The editor matches the user’s bold/italic selection against the weight and style of the entries in the fonts array. If the typeface only contains (.normal, .normal) and (.bold, .normal), italic variants are not selectable. Add the missing Font entries to the typeface to make them available.

Uploaded Font File Is Rejected#

getFontInfo(fontFileURI:) throws EDITOR.FONT_INFO_EXTRACT_FAILED when the file is not a TTF, OTF, WOFF or WOFF2 font. Ask the user for a different file.

Font Info Does Not Load#

getFontInfo(fontFileURI:) throws EDITOR.FONT_LOAD_FAILED when the font URI is not reachable from the device. Check the URL and the App Transport Security configuration.

getTypeface(_:) Throws#

A new .text block does not have an explicit typeface set until setFont(_:fontFileURL:typeface:) is called once. Read with engine.block.getTypefaces(_:in:) (which returns an empty array for 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 the bundled ly.img.typeface/content.json to register the default typefaces.
engine.asset.addLocalSource(sourceID:) Register an empty local asset source. Use ID "ly.img.typeface" to replace the defaults.
engine.asset.addAsset(to:asset:) Add an AssetDefinition to a registered source.
engine.editor.getFontInfo(fontFileURI:) Read the family, subfamily, weight, style and variation axes of a font file.
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.
FontInfo The names, weight, style and variation axes of a font file, as getFontInfo(fontFileURI:) returns them.
VariationAxis One axis of a variable font: tag, minValue, defaultValue and maxValue.
AssetPayload Container for structured asset data; pass a Typeface via payload.typeface.

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, strike-through, and background fill on text