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 render text into one line with a given font? #204

Open
oovm opened this issue Dec 5, 2022 · 1 comment
Open

How to render text into one line with a given font? #204

oovm opened this issue Dec 5, 2022 · 1 comment

Comments

@oovm
Copy link

oovm commented Dec 5, 2022

How can I render a whole line of text into a colored bitmap?

I made some attempts, but encountered the following problems:

  1. The width of the space is 0
  2. Emoji rendering without color.

My render function is as follows

fn render_text(text: &str, font: &Font, font_size: f32) -> anyhow::Result<Canvas> {
    let mut chars = vec![];
    for char in text.chars() {
        let glyph_id = match font.glyph_for_char(char) {
            Some(s) => s,
            None => Err(format!("No such char `{char}` in font `{}`", font.family_name()))?,
        };
        let size = font.raster_bounds(
            glyph_id,
            font_size,
            Transform2F::from_translation(Vector2F::new(0.0, font_size)),
            HintingOptions::None,
            RasterizationOptions::SubpixelAa,
        )?;
        chars.push((glyph_id, size));
    }
    let mut x = 0.0;
    let mut canvas = Canvas::new(Vector2I::new(font_size as i32), Format::A8);
    for (glyph_id, rect) in chars {
        font.rasterize_glyph(
            &mut canvas,
            glyph_id,
            font_size,
            Transform2F::from_translation(Vector2F::new(x, font_size)),
            HintingOptions::None,
            RasterizationOptions::SubpixelAa,
        )?;
        x += rect.size().x() as f32;
    }
    Ok(canvas)
}
@jdm
Copy link
Member

jdm commented Dec 5, 2022

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

2 participants