hecrj / wgpu_glyph

A fast text renderer for wgpu (https://github.com/gfx-rs/wgpu)
https://docs.rs/wgpu_glyph
MIT License
443 stars 77 forks source link

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

Open bokubeam opened 3 years ago

bokubeam commented 3 years ago

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 commented 3 years ago

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 commented 3 years ago

This is helpful, thank you for posting your example!