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

Add examples for text-selection, underlines, etc. #49

Open
bokubeam opened this issue Sep 25, 2020 · 2 comments
Open

Add examples for text-selection, underlines, etc. #49

bokubeam opened this issue Sep 25, 2020 · 2 comments

Comments

@bokubeam
Copy link

I'm working on using wgpu_glyph in the context of a code editor, in particular the ability to show that text has been selected. This is proving more difficult than I anticipated, but seems like a common use case, so once I figure it out I intend to make a PR to add examples for how to go about this. If anyone has already figured this out, I would love to hear how they went about it.

@bjorn-ove
Copy link

I do have a solution, but it is far from ideal. I wanted to look into adding support for this trough code-changes in wgpu_glyph itself, but haven't had time yet.

This is a simplified version of how I ended up doing it. After each draw I can use self.last_bounds + the index of the glyph to
highlight a rect that covers it like a text selection.

Note: To handle whitespace I ended up replacing it with a "_" and making the color invisible. When I used regular whitepace
it does not draw anything and the bound rect was missing causing the indexes to be wrong.

    fn my_draw_text(&mut self, ...) {
        let layout = ...;
        let section = ...;

        // Avoid re-allocating new vec's every time by storing them internally
        self.last_glyphs.clear();
        self.last_bounds.clear();

        // Get all the glyphs for the current section to calculate their bounds. Due to
        // mutable borrow, this must be stored first.
        self.last_glyphs
            .extend(self.brush.glyphs_custom_layout(&s, &layout).cloned());

        // Calculate the bounds of each glyph
        self.last_bounds
            .extend(self.last_glyphs.iter().map(|glyph| {
                let bounds = &fonts[glyph.font_id.0].glyph_bounds(&glyph.glyph);
                Rect::new(
                    Vec2::new(bounds.min.x, bounds.min.y),
                    Vec2::new(bounds.max.x, bounds.max.y),
                )
            }));

        // Queue the glyphs for drawing
        self.brush.queue_custom_layout(s, &layout);
    }

@bokubeam
Copy link
Author

bokubeam commented Nov 2, 2020

This is helpful, thank you for posting your example!

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