Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to draw centred text using GlyphCache #330

Open
AleCamara opened this issue Dec 27, 2020 · 0 comments
Open

How to draw centred text using GlyphCache #330

AleCamara opened this issue Dec 27, 2020 · 0 comments

Comments

@AleCamara
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant