ggez 图形中不提供字体

问题描述 投票:0回答:1

如何设置文本字体?

需要使用 ggez 引擎在屏幕上显示简单的文本。但出现这些错误:

error[E0433]: failed to resolve: could not find `Font` in `graphics`
  --> src/main.rs:11:30
   |
11 |         let font = graphics::Font::default();
   |                              ^^^^ could not find `Font` in `graphics`

代码:

use ggez::{event, graphics, input, Context, GameResult};
use std::env;
use std::path;

struct MainState {
    font: graphics::Font,
}

impl MainState {
    fn new(ctx: &mut Context) -> GameResult<MainState> {
        let font = graphics::Font::new(ctx, "/path/to/font.ttf")?; // lets say, Font.Default();
        Ok(MainState { font })
    }
}

impl event::EventHandler for MainState {
    fn update(&mut self, _ctx: &mut Context) -> GameResult {
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        graphics::clear(ctx, [1.0, 1.0, 1.0, 1.0].into());

        let text = "Hello World!";
        let text_fragment = graphics::Text::new((text, self.font, 24.0));
        let text_dimensions = graphics::dimensions(ctx, &text_fragment)?;
        let text_position = graphics::Point2::new(
            (graphics::screen_width(ctx) - text_dimensions.w) / 2.0,
            (graphics::screen_height(ctx) - text_dimensions.h) / 2.0,
        );
        graphics::draw(ctx, &text_fragment, (text_position,))?;

        graphics::present(ctx)?;

        Ok(())
    }
}

fn main() -> GameResult {
    let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
        let mut path = path::PathBuf::from(manifest_dir);
        path.push("resources");
        path
    } else {
        path::PathBuf::from("./resources")
    };

    let (mut ctx, mut event_loop) = ggez::ContextBuilder::new("hello_world", "ggez")
        .add_resource_path(resource_dir)
        .build()
        .expect("aieee, could not create ggez context!");

    let state = MainState::new(&mut ctx)?;
    event::run(ctx, event_loop, state)
}
rust ggez
1个回答
0
投票

0.7.1之前的版本有ggez::graphics::Font,但以后的版本不再有。似乎没有任何发行说明提到这一点,因为 0.8.0 似乎没有发行说明。

无论如何,如果你看看 0.7.1 中的 TextFragment 结构

pub struct TextFragment { pub text: String, pub color: Option<Color>, pub font: Option<Font>, pub scale: Option<PxScale>, }
0.9.3 中的

pub struct TextFragment { pub text: String, pub font: Option<String>, pub scale: Option<PxScale>, pub color: Option<Color>, }

然后很明显 
Font

被替换为普通的

String
    

© www.soinside.com 2019 - 2024. All rights reserved.