在 Piston2d 中呈现文本的函数中的 GlyphCache 类型是什么

What is GlyphCache type in a function to render text in Piston2d

我正在尝试编写一个单独的函数来使用 piston2d 呈现文本。以 hello_world.rs 为例,我试图扩展它以允许我从函数内呈现文本。

这是我写的代码:

extern crate piston_window;
extern crate find_folder;

use piston_window::*;

fn main() {
    let mut window: PistonWindow = WindowSettings::new(
            "piston: try to render text",
            [200, 200]
        )
        .exit_on_esc(true)
        .build()
        .unwrap();

    let assets = find_folder::Search::ParentsThenKids(3, 3)
        .for_folder("assets").unwrap();
    println!("{:?}", assets);
    let ref font = assets.join("FiraSans-Regular.ttf");
    let factory = window.factory.clone();
    let mut glyphs = Glyphs::new(font, factory, TextureSettings::new()).unwrap();

    window.set_lazy(true);
    while let Some(e) = window.next() {
        window.draw_2d(&e, |c, mut g| {
            clear([0.0, 0.0, 0.0, 1.0], g);
            render_text(10.0, 100.0, "Hello World", 32, c, &mut g, &mut glyphs);
        });
    }
}

fn render_text(x: f64, y: f64,
               text: &str, size: u32,
               c: Context, g: &mut G2d, 
               glyphs: &mut glyph_cache::rusttype::GlyphCache<GfxFactory, G2dTexture>) {
    text::Text::new(size).draw(
           text,
           &mut glyphs,
           &c.draw_state,
           c.transform.trans(x, y),
           g
        ).unwrap();
} 

当我尝试 运行 这段代码时,出现以下错误:

error[E0277]: the trait bound `&mut piston_window::glyph_cache::rusttype::GlyphCache<'_, gfx_device_gl::factory::Factory, piston_window::Texture<gfx_device_gl::Resources>>: piston_window::character::CharacterCache` is not satisfied

the trait `piston_window::character::CharacterCache` is not implemented for `&mut piston_window::glyph_cache::rusttype::GlyphCache<'_, gfx_device_gl::factory::Factory, piston_window::Texture<gfx_device_gl::Resources>>`

我已经为 glyphs 尝试了很多不同的类型,这是我能做到的最远的。

类型应该是什么? 任何指导表示赞赏。

问题是您将对 GlyphCache 的可变引用的可变引用传递给 draw()render_text 收到一个可变引用,然后您创建了一个可变引用那个)。只需在 draw().

的调用中将 &mut glyphs 更改为 glyphs

draw() 期望对实现 Graphics<Texture = <C as CharacterCache>::Texture> 的类型的可变引用,并且 GlyphCache<GfxFactory, G2dTexture> 确实实现了该特征,但 &mut GlyphCache<GfxFactory, G2dTexture> 没有。

当函数参数的类型是具体类型时,编译器将自动解除对引用的引用以匹配预期的类型(Clippy 有一个 lint 来识别创建不必要引用的地方)。但是,当函数参数的类型是泛型类型时(就像这里的情况),编译器不会尝试这样做。