Skip to content

Commit

Permalink
add draw_align to graphics::Text
Browse files Browse the repository at this point in the history
  • Loading branch information
Chen1Plus committed Jan 27, 2024
1 parent 837849c commit f18ebb4
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion src/graphics/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ mod packer;
mod vector;

use std::cell::RefCell;
use std::fmt::{self, Debug, Formatter};
use std::fmt::{self, Alignment, Debug, Formatter};
use std::path::Path;
use std::rc::Rc;

Expand Down Expand Up @@ -255,6 +255,46 @@ impl Text {
}
}

/// Same as draw but with alignment option.
pub fn draw_align<P>(&mut self, ctx: &mut Context, params: P, align: Alignment)
where
P: Into<DrawParams>,
{
self.update_geometry(ctx);

let data = self.font.data.borrow();
let texture = data.texture();
let geometry = self
.geometry
.as_ref()
.expect("geometry should have been generated");

let mut params = params.into();
params.position.x -= match align {
Alignment::Left => 0.0,
Alignment::Center => geometry.bounds.unwrap().width / 2.0,
Alignment::Right => geometry.bounds.unwrap().width,
};

graphics::set_texture(ctx, texture);
let (texture_width, texture_height) = texture.size();

for quad in &geometry.quads {
graphics::push_quad(
ctx,
quad.position.x,
quad.position.y,
quad.position.x + quad.region.width,
quad.position.y + quad.region.height,
quad.region.x / (texture_width as f32),
quad.region.y / (texture_height as f32),
quad.region.right() / (texture_width as f32),
quad.region.bottom() / (texture_height as f32),
&params,
);
}
}

/// Returns a reference to the content of the text.
pub fn content(&self) -> &str {
&self.content
Expand Down

0 comments on commit f18ebb4

Please sign in to comment.