Pure-Swift reading of the True Type Font (.ttf) file format, and conformance to SwiftGraphicsCore
's Font
.
This is a work in progress. The TrueType / OpenType font specs are massive, https://docs.microsoft.com/en-us/typography/opentype/spec/otff,https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html#FDEF.
.ttf
fileimport SwiftGraphicsCore
import SwiftTrueTypeFont
let data:Data = ... //read data from a *.ttf or *.otf file.
let trueTypeFont:TrueTypeFont? = try? TrueTypeFont(data:data)
TrueTypeFont
comforms to SwiftGraphicsCore
's Font
, which means that in order to render it, you have to provide values for the options. In particular, you need to provide an option value for the size in order to obtain a RenderingFont
. Only a RenderingFont
can make glyphs directly.
Here's an example of getting a rendering font with size 14.0 from the font.
let font:Font = trueTypeFont
let values:[FontOptionValue] = font.options.compactMap({ option in
guard option.name == String.FontOptionNameSize else { return nil }
return option.value(14.0)
})
guard let renderingFont:RenderingFont = font.rendering(options:values) else { /* fail */ }
The rendering font can then be used with the drawText(
method on any GraphicsContext
.
UIFont(name:...
in iOS.let name:String? = font.postScriptName
Conveniences for reading MSBs from Data
are in Data+MSB.swift
Feel free to contribute; I'm a stickler for making things "Swifty", because I love Swift as a language. Any functions you write should feature two paths: a detailed path suitable for introspection and throw errors meaningful to a developer who wants to examine the validity of the font, and a simple path that gets a font user quick access to things they want.
Currently cmap formats 0, 4, 6 and 12 are supported.
I don't plan to support format 2 because it only supports mixed 8/16-bit encodings directly, and we're getting the utf-8 byte stream after the multi-byte encodings have been flattened.
I don't plan to support formats 8 or 10 because their use is very rare.
I don't plan to support 13 because I don't plan to support "last resort" fonts, but maybe that will change.
I don't plan to support 14 because I don't plan to support variation sequences.
(Instucting cannot be activated until all instructions are correctly interpretted)
link |
Stars: 1 |
Last commit: 3 years ago |
Also improve conversion of bytes to integers and back again.
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics