Skip to main content

Crate font_shape

Crate font_shape 

Source
Expand description

Glyph rasterization and text measurement — scanline fill, stroke expansion, advance/kerning layout, and bidirectional reordering.

font-shape is the estate’s L2 shaping layer: the half of a font toolchain that turns a font_model::Font into pixels and into measured text. It sits on [font-model] (L1), which sits on font-parse (L0).

use font_model::{Font, Glyph, GlyphId, Outline, Path};
use font_shape::{rasterize_glyph, shape_line, Hinting};

// A 1000-upem font with one square glyph, 500 units wide.
let mut outline = Outline::new();
let mut p = Path::starting_at(50.0, 0.0);
p.line_to(450.0, 0.0);
p.line_to(450.0, 700.0);
p.line_to(50.0, 700.0);
p.close();
outline.push_contour(p);

let font = Font::builder()
    .units_per_em(1000)
    .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
    .glyph(Glyph::new(GlyphId::new(1), 500, 50, outline))
    .build()
    .expect("a one-glyph font is valid");

// Rasterize at 20 px: an 8x14 block, 20 rows above the baseline.
let bmp = rasterize_glyph(&font, GlyphId::new(1), 20.0, Hinting::None)?;
assert_eq!((bmp.width(), bmp.height()), (8, 14));
assert_eq!(bmp.top(), 14);
assert!(bmp.ink() > 100.0);

// Measure the run: one glyph, 500 units at 20 px = 10 px.
let line = shape_line(&font, "A", 20.0)?;
assert_eq!(line.len(), 1);
assert!((line.advance_px() - 10.0).abs() < 1e-4);

§What is in here

AreaEntry points
transformsAffine2D
pathsPath2D, PathBuilder with a transform stack
fillingfill_path — exact analytic coverage, FillRule
strokingstroke_path — expand to an outline, then fill
glyphsrasterize_glyph, rasterize_outline, Hinting, GlyphBitmap
textshape_line, measure_run, measure_glyph, resolve_bidi

§The rasterizer

fill_path computes the exact area each pixel covers, integrating the span coverage analytically rather than supersampling. Two properties follow, and both are asserted in the test suite:

  • An axis-aligned rectangle on integer boundaries is exactly 255 in its interior and 0 outside; shifted half a pixel it is exactly 128 on each edge.
  • A mask’s total coverage equals the polygon it came from: for a 64-unit right triangle, the ink matches ½·64·64 to within 0.1 %. That single number bounds every antialiasing claim this crate makes.

Device space is y down, pixel (x, y) covering [x, x+1) × [y, y+1). rasterize_glyph flips a font’s y-up outline into that space and carries all intermediate arithmetic in 26.6 fixed point, so a glyph lands on the pixel grid the same way at 12 px and 144 px.

use font_shape::{fill_path, FillRule, PathBuilder};

let mut b = PathBuilder::new();
b.rect(0.5, 0.0, 4.0, 1.0);
let mask = fill_path(&b.build(), FillRule::NonZero, 8, 1)?;

assert_eq!(mask[0], 128, "half a pixel of coverage is exactly 128");
assert_eq!(mask[1], 255);
assert_eq!(mask[4], 128);
assert_eq!(mask[5], 0);

§Layer

L2 — domain. Its only estate-internal dependency is font-model (L1). libm supplies the no_std transcendentals and thiserror the error taxonomy. There is deliberately no image or rasterizer dependency: the scanline filler is the point of the crate.

Structs§

Affine2D
A 2D affine transform: scale, rotate, skew, then translate.
BidiLevels
Resolved per-character embedding levels for a line of text.
DeviceMetrics
Font metrics resolved to device pixels.
GlyphBitmap
A glyph’s coverage: 8 bits per pixel, with the placement a caller needs to put it back into a text run.
GlyphPlacement
One glyph’s place in a shaped line.
Path2D
A device-space path: a list of subpaths of absolute segments.
PathBuilder
Accumulates a Path2D through a transform stack.
Rect
An axis-aligned rectangle, used for a path’s or bitmap’s bounds.
ShapedLine
A shaped line of text: glyphs, their pen positions, and the run’s metrics.
StrokeStyle
A stroke’s width, caps, joins, and miter limit.

Enums§

BidiClass
The Unicode bidirectional categories this module distinguishes.
FillRule
Which rule decides whether a point is inside the path.
Hinting
How a glyph’s outline is snapped to the pixel grid.
LayoutDirection
Which way a run reads.
LineCap
How the ends of an open subpath are finished.
LineJoin
How the corners between two segments are finished.
PathCommand
One resolved path segment, absolute.
ShapeError
The single crate-level error for rasterization and measurement.

Constants§

DEFAULT_MITER_LIMIT
The default miter limit: a miter longer than this many stroke widths is beveled instead. Matches SVG’s stroke-miterlimit default.
MAX_MASK_ELEMENTS
The largest mask this crate will allocate: 4096 × 4096 = 16 MiB of coverage.
PIXEL
One pixel, in 26.6 fixed point.
PIXEL_FP_BITS
The number of fractional bits in a 26.6 fixed-point value.
VERSION
The crate’s version, for callers that report it.

Functions§

ascii_cmap
A cmap mapping A and B to glyphs 1 and 2. Exists for the doctests, which each need a font that actually resolves the characters they measure.
bidi_class
The bidirectional class of a character.
describe_run
A short description of a run, for diagnostics.
em_size_px
The device pixel size of the em square at size_px.
fill_path
Fill path into an 8-bit coverage mask width × height.
fixed_scale
The scale from font units to 26.6 fixed-point units: size_px · 64 / upem.
from_fixed
A 26.6 fixed-point integer back to pixels.
glyph_path
The device-space path for a glyph in a font.
glyph_path_from_outline
The device-space path for a font outline: pixels, y down, origin on the baseline at the glyph’s x origin.
grid_fit
Snap a 26.6 value to the nearest pixel boundary.
is_rtl_level
The embedding level of one character in a resolved line: even is LTR, odd is RTL.
mask_coverage
The total coverage of a mask, in 0..255 units. Dividing by 255 gives the ink area in pixels.
measure_glyph
The advance width of a single glyph in pixels, no kerning.
measure_run
The advance width of a run of characters in pixels, kerning included.
message
The message a ShapeError carries, for diagnostics in a host that cannot propagate the type.
path_pixel_bounds
The tight pixel bounds a path occupies in a raster of the given size, or None when it covers nothing.
rasterize_glyph
Rasterize a glyph from a font.
rasterize_outline
Rasterize an outline into a bitmap placed relative to the baseline.
reorder_indices
Reorder logical indices for display under rule L2.
resolve_bidi
Resolve embedding levels for text under UAX #9 rules P2/P3, W, N, and I.
resolve_bidi_chars
resolve_bidi over an explicit character slice, so a caller that already split the text does not pay for a second pass.
scaled_metrics
Font metrics in device pixels, y down, origin on the baseline.
set_explicit_levels
Set explicit embedding levels on a resolved set.
shape_line
Lay out a line of text: glyphs, pen positions, kerning, and bidi order.
shape_line_with
shape_line with an explicit direction.
stroke_path
Expand a stroke into the outline of the region it covers.
to_26_6
A value that is already in 26.6 units, rounded to the nearest integer.
to_fixed
value as a 26.6 fixed-point integer, rounded to nearest and saturating.

Type Aliases§

Result
A convenience alias for this crate’s error.