extern crate rusttype;
use rusttype::{FontCollection, Scale, point, PositionedGlyph};
use std::io::Write;
fn main() {
let font_data = include_bytes!("../fonts/wqy-microhei/WenQuanYiMicroHei.ttf");
let collection = FontCollection::from_bytes(font_data as &[u8]);
let font = collection.into_font().unwrap();
let height: f32 = 12.4; let pixel_height = height.ceil() as usize;
let scale = Scale { x: height*2.0, y: height };
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
let glyphs: Vec<PositionedGlyph> = font.layout("RustType", scale, offset).collect();
let width = glyphs.iter().rev()
.map(|g| g.position().x as f32 + g.unpositioned().h_metrics().advance_width)
.next().unwrap_or(0.0).ceil() as usize;
println!("width: {}, height: {}", width, pixel_height);
let mut pixel_data = vec![b'@'; width * pixel_height];
let mapping = b"@%#x+=:-. "; let mapping_scale = (mapping.len()-1) as f32;
for g in glyphs {
if let Some(bb) = g.pixel_bounding_box() {
g.draw(|x, y, v| {
let i = (v*mapping_scale + 0.5) as usize;
let c = mapping.get(i).cloned().unwrap_or(b'$');
let x = x as i32 + bb.min.x;
let y = y as i32 + bb.min.y;
if x >= 0 && x < width as i32 && y >= 0 && y < pixel_height as i32 {
let x = x as usize;
let y = y as usize;
pixel_data[(x + y * width)] = c;
}
})
}
}
let stdout = ::std::io::stdout();
let mut handle = stdout.lock();
for j in 0..pixel_height {
handle.write(&pixel_data[j*width..(j+1)*width]).unwrap();
handle.write(b"\n").unwrap();
}
}