5个版本

使用旧的Rust 2015

0.1.4 2016年5月18日
0.1.3 2016年5月18日
0.1.2 2016年5月17日
0.1.1 2016年5月17日
0.1.0 2016年5月17日

20 in #bitmap-font

MIT 协议

27KB
121

rust-bmfont

为rustlang提供的位图字体解析器。目前支持

用法

返回一个包含.fnt (xml格式)中信息的结构体,可供渲染器处理。

extern crate bmfont;

use bmfont::{ parse as bmparse };
use std::path::{ PathBuf, Path };
use std::env;

fn main() {
    let cwd: PathBuf = env::current_dir().unwrap();
    let assetspath: PathBuf = PathBuf::from(cwd).join(Path::new("examples/assets"));
    let fontdescriptorpath: PathBuf = assetspath.join(Path::new("font.fnt"));

    let res = bmparse(fontdescriptorpath);
    println!("{:?}", res);
}

示例

解析示例

$ cargo run --example parse

示例渲染器

// file: text_renderer.rs

extern crate graphics;
extern crate bmfont;

use opengl_graphics::{ GlGraphics, Texture as GlTexture };
use piston_window::{ Context, Image };

use graphics::DrawState;

use bmfont::{ BmFont };

pub struct TextRenderer {
    pub texture: GlTexture,
    map: BmFont
}

impl TextRenderer {

    pub fn new(font: BmFont) -> Self {
        TextRenderer {
            texture: GlTexture::from_path(&(font.pages[0]).file).unwrap(),
            map: font
        }
    }

    pub fn render(
        &self,
        text: String,
        center_x: f64,
        center_y: f64,
        color: [f32; 4],
        c: &Context,
        gl: &mut GlGraphics
    ) {

        let mut x = center_x;
        let y = center_y;

        for character in text.chars() {

            let charcode = character as u32;
            //let bmchar: &BmChar;

            if let Some(bmchar) = self.map.chars.get(&charcode) {
                Image::new_color([color[0], color[1], color[2], color[3]])
                    .src_rect([bmchar.x as i32, bmchar.y as i32, bmchar.width as i32, bmchar.height as i32])
                    .rect([x as f64, y + bmchar.yoffset as f64, bmchar.width as f64, bmchar.height as f64])
                    .draw(
                        &self.texture,
                        &DrawState::default(),
                        c.transform,
                        gl
                    );

                x += bmchar.width as f64 + bmchar.xoffset as f64;
            }
        }
    }
}

在您的程序中,可以使用位图字体渲染器如下

// [...]
mod text_renderer;
use text_renderer::TextRenderer;

// [...] During init
let cwd: PathBuf = env::current_dir().unwrap();
let assetspath: PathBuf = PathBuf::from(cwd).join(Path::new("assets/font"));
let fontdescriptorpath: PathBuf = assetspath.join(Path::new("myfont.fnt"));

let textr = TextRenderer::new(bmparse(fontdescriptorpath));

// [...] In your render method
const BLACK:[f32; 4] = [0.0, 0.0, 0.0, 1.0];

textr.render(
  String::from("Hello, World !"),  // The string to render
  200.0, // posx
  200.0,// posy
  BLACK, // Color
  &c,    // Piston window Context; passed in gl.draw callback; may be built using let ref c = Context::new_abs(viewwidth as f64, viewheight as f64);
  &mut gl    // GlGraphics object
);

依赖项

~405KB