Struct ttf_parser::Face

source ·
pub struct Face<'a> { /* private fields */ }
Expand description

A font face.

Provides a high-level API for working with TrueType fonts. If you’re not familiar with how TrueType works internally, you should use this type. If you do know and want a bit more low-level access - checkout FaceTables.

Note that Face doesn’t own the font data and doesn’t allocate anything in heap. Therefore you cannot “store” it. The idea is that you should parse the Face when needed, get required data and forget about it. That’s why the initial parsing is highly optimized and should not become a bottleneck.

If you still want to store Face - checkout owned_ttf_parser. Requires unsafe.

While Face is technically copyable, we disallow it because it’s almost 2KB big.

Implementations§

source§

impl<'a> Face<'a>

source

pub fn from_slice(data: &'a [u8], index: u32) -> Result<Self, FaceParsingError>

👎Deprecated since 0.16.0: use parse instead

Creates a new Face from a raw data.

index indicates the specific font face in a font collection. Use fonts_in_collection to get the total number of font faces. Set to 0 if unsure.

This method will do some parsing and sanitization, but in general can be considered free. No significant performance overhead.

Required tables: head, hhea and maxp.

If an optional table has invalid data it will be skipped.

source

pub fn parse(data: &'a [u8], index: u32) -> Result<Self, FaceParsingError>

Creates a new Face from a raw data.

index indicates the specific font face in a font collection. Use fonts_in_collection to get the total number of font faces. Set to 0 if unsure.

This method will do some parsing and sanitization, but in general can be considered free. No significant performance overhead.

Required tables: head, hhea and maxp.

If an optional table has invalid data it will be skipped.

source

pub fn from_raw_tables( raw_tables: RawFaceTables<'a> ) -> Result<Self, FaceParsingError>

Creates a new Face from provided RawFaceTables.

source

pub fn tables(&self) -> &FaceTables<'a>

Returns low-level face tables.

source

pub fn raw_face(&self) -> &RawFace<'a>

Returns the RawFace used to create this Face.

Useful if you want to parse the data manually.

Available only for faces created using Face::parse().

source

pub fn table_data(&self, tag: Tag) -> Option<&'a [u8]>

👎Deprecated since 0.16.0: use self.raw_face().table() instead

Returns the raw data of a selected table.

Useful if you want to parse the data manually.

Available only for faces created using Face::parse().

source

pub fn names(&self) -> Names<'a>

Returns a list of names.

Contains face name and other strings.

source

pub fn is_regular(&self) -> bool

Checks that face is marked as Regular.

Returns false when OS/2 table is not present.

source

pub fn is_italic(&self) -> bool

Checks that face is marked as Italic.

Returns false when OS/2 table is not present.

source

pub fn is_bold(&self) -> bool

Checks that face is marked as Bold.

Returns false when OS/2 table is not present.

source

pub fn is_oblique(&self) -> bool

Checks that face is marked as Oblique.

Returns false when OS/2 table is not present or when its version is < 4.

source

pub fn style(&self) -> Style

Returns face style.

source

pub fn is_monospaced(&self) -> bool

Checks that face is marked as Monospaced.

Returns false when post table is not present.

source

pub fn is_variable(&self) -> bool

Checks that face is variable.

Simply checks the presence of a fvar table.

source

pub fn weight(&self) -> Weight

Returns face’s weight.

Returns Weight::Normal when OS/2 table is not present.

source

pub fn width(&self) -> Width

Returns face’s width.

Returns Width::Normal when OS/2 table is not present or when value is invalid.

source

pub fn italic_angle(&self) -> Option<f32>

Returns face’s italic angle.

Returns None when post table is not present.

source

pub fn ascender(&self) -> i16

Returns a horizontal face ascender.

This method is affected by variation axes.

source

pub fn descender(&self) -> i16

Returns a horizontal face descender.

This method is affected by variation axes.

source

pub fn height(&self) -> i16

Returns face’s height.

This method is affected by variation axes.

source

pub fn line_gap(&self) -> i16

Returns a horizontal face line gap.

This method is affected by variation axes.

source

pub fn typographic_ascender(&self) -> Option<i16>

Returns a horizontal typographic face ascender.

Prefer Face::ascender unless you explicitly want this. This is a more low-level alternative.

This method is affected by variation axes.

Returns None when OS/2 table is not present.

source

pub fn typographic_descender(&self) -> Option<i16>

Returns a horizontal typographic face descender.

Prefer Face::descender unless you explicitly want this. This is a more low-level alternative.

This method is affected by variation axes.

Returns None when OS/2 table is not present.

source

pub fn typographic_line_gap(&self) -> Option<i16>

Returns a horizontal typographic face line gap.

Prefer Face::line_gap unless you explicitly want this. This is a more low-level alternative.

This method is affected by variation axes.

Returns None when OS/2 table is not present.

source

pub fn vertical_ascender(&self) -> Option<i16>

Returns a vertical face ascender.

This method is affected by variation axes.

source

pub fn vertical_descender(&self) -> Option<i16>

Returns a vertical face descender.

This method is affected by variation axes.

source

pub fn vertical_height(&self) -> Option<i16>

Returns a vertical face height.

This method is affected by variation axes.

source

pub fn vertical_line_gap(&self) -> Option<i16>

Returns a vertical face line gap.

This method is affected by variation axes.

source

pub fn units_per_em(&self) -> u16

Returns face’s units per EM.

Guarantee to be in a 16..=16384 range.

source

pub fn x_height(&self) -> Option<i16>

Returns face’s x height.

This method is affected by variation axes.

Returns None when OS/2 table is not present or when its version is < 2.

source

pub fn capital_height(&self) -> Option<i16>

Returns face’s capital height.

This method is affected by variation axes.

Returns None when OS/2 table is not present or when its version is < 2.

source

pub fn underline_metrics(&self) -> Option<LineMetrics>

Returns face’s underline metrics.

This method is affected by variation axes.

Returns None when post table is not present.

source

pub fn strikeout_metrics(&self) -> Option<LineMetrics>

Returns face’s strikeout metrics.

This method is affected by variation axes.

Returns None when OS/2 table is not present.

source

pub fn subscript_metrics(&self) -> Option<ScriptMetrics>

Returns face’s subscript metrics.

This method is affected by variation axes.

Returns None when OS/2 table is not present.

source

pub fn superscript_metrics(&self) -> Option<ScriptMetrics>

Returns face’s superscript metrics.

This method is affected by variation axes.

Returns None when OS/2 table is not present.

source

pub fn permissions(&self) -> Option<Permissions>

Returns face permissions.

Returns None in case of a malformed value.

source

pub fn is_subsetting_allowed(&self) -> bool

Checks if the face subsetting is allowed.

source

pub fn is_bitmap_embedding_allowed(&self) -> bool

Checks if the face bitmaps embedding is allowed.

source

pub fn unicode_ranges(&self) -> UnicodeRanges

Checks if the face bitmaps embedding is allowed.

source

pub fn number_of_glyphs(&self) -> u16

Returns a total number of glyphs in the face.

Never zero.

The value was already parsed, so this function doesn’t involve any parsing.

source

pub fn glyph_index(&self, code_point: char) -> Option<GlyphId>

Resolves a Glyph ID for a code point.

Returns None instead of 0 when glyph is not found.

All subtable formats except Mixed Coverage (8) are supported.

If you need a more low-level control, prefer Face::tables().cmap.

source

pub fn glyph_index_by_name(&self, name: &str) -> Option<GlyphId>

Resolves a Glyph ID for a glyph name.

Uses the post and CFF tables as sources.

Returns None when no name is associated with a glyph.

source

pub fn glyph_variation_index( &self, code_point: char, variation: char ) -> Option<GlyphId>

Resolves a variation of a Glyph ID from two code points.

Implemented according to Unicode Variation Sequences.

Returns None instead of 0 when glyph is not found.

source

pub fn glyph_hor_advance(&self, glyph_id: GlyphId) -> Option<u16>

Returns glyph’s horizontal advance.

This method is affected by variation axes.

source

pub fn glyph_ver_advance(&self, glyph_id: GlyphId) -> Option<u16>

Returns glyph’s vertical advance.

This method is affected by variation axes.

source

pub fn glyph_hor_side_bearing(&self, glyph_id: GlyphId) -> Option<i16>

Returns glyph’s horizontal side bearing.

This method is affected by variation axes.

source

pub fn glyph_ver_side_bearing(&self, glyph_id: GlyphId) -> Option<i16>

Returns glyph’s vertical side bearing.

This method is affected by variation axes.

source

pub fn glyph_y_origin(&self, glyph_id: GlyphId) -> Option<i16>

Returns glyph’s vertical origin according to Vertical Origin Table.

source

pub fn glyph_name(&self, glyph_id: GlyphId) -> Option<&str>

Returns glyph’s name.

Uses the post and CFF tables as sources.

Returns None when no name is associated with a glyph.

source

pub fn outline_glyph( &self, glyph_id: GlyphId, builder: &mut dyn OutlineBuilder ) -> Option<Rect>

Outlines a glyph and returns its tight bounding box.

Warning: since ttf-parser is a pull parser, OutlineBuilder will emit segments even when outline is partially malformed. You must check outline_glyph() result before using OutlineBuilder’s output.

gvar, glyf, CFF and CFF2 tables are supported. And they will be accesses in this specific order.

This method is affected by variation axes.

Returns None when glyph has no outline or on error.

Example
use std::fmt::Write;
use ttf_parser;

struct Builder(String);

impl ttf_parser::OutlineBuilder for Builder {
    fn move_to(&mut self, x: f32, y: f32) {
        write!(&mut self.0, "M {} {} ", x, y).unwrap();
    }

    fn line_to(&mut self, x: f32, y: f32) {
        write!(&mut self.0, "L {} {} ", x, y).unwrap();
    }

    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
        write!(&mut self.0, "Q {} {} {} {} ", x1, y1, x, y).unwrap();
    }

    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
        write!(&mut self.0, "C {} {} {} {} {} {} ", x1, y1, x2, y2, x, y).unwrap();
    }

    fn close(&mut self) {
        write!(&mut self.0, "Z ").unwrap();
    }
}

let data = std::fs::read("tests/fonts/demo.ttf").unwrap();
let face = ttf_parser::Face::parse(&data, 0).unwrap();
let mut builder = Builder(String::new());
let bbox = face.outline_glyph(ttf_parser::GlyphId(1), &mut builder).unwrap();
assert_eq!(builder.0, "M 173 267 L 369 267 L 270 587 L 173 267 Z M 6 0 L 224 656 \
                       L 320 656 L 541 0 L 452 0 L 390 200 L 151 200 L 85 0 L 6 0 Z ");
assert_eq!(bbox, ttf_parser::Rect { x_min: 6, y_min: 0, x_max: 541, y_max: 656 });
source

pub fn glyph_bounding_box(&self, glyph_id: GlyphId) -> Option<Rect>

Returns a tight glyph bounding box.

This is just a shorthand for outline_glyph() since only the glyf table stores a bounding box. We ignore glyf table bboxes because they can be malformed. In case of CFF and variable fonts we have to actually outline a glyph to find it’s bounding box.

When a glyph is defined by a raster or a vector image, that can be obtained via glyph_image(), the bounding box must be calculated manually and this method will return None.

Note: the returned bbox is not validated in any way. A font file can have a glyph bbox set to zero/negative width and/or height and this is perfectly ok. For calculated bboxes, zero width and/or height is also perfectly fine.

This method is affected by variation axes.

source

pub fn global_bounding_box(&self) -> Rect

Returns a bounding box that large enough to enclose any glyph from the face.

source

pub fn glyph_raster_image( &self, glyph_id: GlyphId, pixels_per_em: u16 ) -> Option<RasterGlyphImage<'_>>

Returns a reference to a glyph’s raster image.

A font can define a glyph using a raster or a vector image instead of a simple outline. Which is primarily used for emojis. This method should be used to access raster images.

pixels_per_em allows selecting a preferred image size. The chosen size will be closer to an upper one. So when font has 64px and 96px images and pixels_per_em is set to 72, 96px image will be returned. To get the largest image simply use std::u16::MAX.

Note that this method will return an encoded image. It should be decoded by the caller. We don’t validate or preprocess it in any way.

Also, a font can contain both: images and outlines. So when this method returns None you should also try outline_glyph() afterwards.

There are multiple ways an image can be stored in a TrueType font and this method supports most of them. This includes sbix, bloc + bdat, EBLC + EBDT, CBLC + CBDT. And font’s tables will be accesses in this specific order.

source

pub fn glyph_svg_image(&self, glyph_id: GlyphId) -> Option<SvgDocument<'a>>

Returns a reference to a glyph’s SVG image.

A font can define a glyph using a raster or a vector image instead of a simple outline. Which is primarily used for emojis. This method should be used to access SVG images.

Note that this method will return just an SVG data. It should be rendered or even decompressed (in case of SVGZ) by the caller. We don’t validate or preprocess it in any way.

Also, a font can contain both: images and outlines. So when this method returns None you should also try outline_glyph() afterwards.

source

pub fn is_color_glyph(&self, glyph_id: GlyphId) -> bool

Returns true if the glyph can be colored/painted using the COLR+CPAL tables.

See paint_color_glyph for details.

source

pub fn color_palettes(&self) -> Option<NonZeroU16>

Returns the number of palettes stored in the COLR+CPAL tables.

See paint_color_glyph for details.

source

pub fn paint_color_glyph( &self, glyph_id: GlyphId, palette: u16, painter: &mut dyn Painter ) -> Option<()>

Paints a color glyph from the COLR table.

A font can have multiple palettes, which you can check via color_palettes. If unsure, just pass 0 to the palette argument, which is the default.

A font can define a glyph using layers of colored shapes instead of a simple outline. Which is primarily used for emojis. This method should be used to access glyphs defined in the COLR table.

Also, a font can contain both: a layered definition and outlines. So when this method returns None you should also try outline_glyph afterwards.

Returns None if the glyph has no COLR definition or if the glyph definition is malformed.

See examples/font2svg.rs for usage examples.

source

pub fn variation_axes(&self) -> LazyArray16<'a, VariationAxis>

Returns an iterator over variation axes.

source

pub fn set_variation(&mut self, axis: Tag, value: f32) -> Option<()>

Sets a variation axis coordinate.

This is the only mutable method in the library. We can simplify the API a lot by storing the variable coordinates in the face object itself.

Since coordinates are stored on the stack, we allow only 32 of them.

Returns None when face is not variable or doesn’t have such axis.

source

pub fn variation_coordinates(&self) -> &[NormalizedCoordinate]

Returns the current normalized variation coordinates.

source

pub fn has_non_default_variation_coordinates(&self) -> bool

Checks that face has non-default variation coordinates.

Trait Implementations§

source§

impl<'a> Clone for Face<'a>

source§

fn clone(&self) -> Face<'a>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Face<'_>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> RefUnwindSafe for Face<'a>

§

impl<'a> Send for Face<'a>

§

impl<'a> Sync for Face<'a>

§

impl<'a> Unpin for Face<'a>

§

impl<'a> UnwindSafe for Face<'a>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.