Skip to content

How to draw centred text using GlyphCache #330

Open
@AleCamara

Description

@AleCamara

I'm finding it hard to draw text centred around a point in the screen.

GlyphCache is probably too low-level to offer this functionality directly, but it could help with a

calculate_text_width(&self, text: &str, size: FontSize) -> Scalar

method to calculate the expected width of a given text and font size. How do you feel about this?

I'm currently exploring the avenue of preloading all chars of the text, then getting the character with opt_character(), and using advance_width() to calculate the final width.

pub fn calculate_text_width<'a>(text: &str, font_size: FontSize, glyphs: &'a GlyphCache) -> f32 {
    let mut w = 0.0;
    glyphs.preload_chars(font_size, text.chars());
    for c in text.chars() {
        if let Some(ch) = glyphs.opt_character(font_size, c) {
            w += ch.advance_width() as f32;
        }
    }
    w
}

But this feels cumbersome, and something so useful that should be provided by the library directly, no?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions