Add Align property to TextView

Can change its horizontal and vertical alignment for when the allocated
size is bigger than the requirements.
This commit is contained in:
Alexandre Bury 2015-06-01 17:48:29 -07:00
parent 2a423b8408
commit 1656cdd8f6
3 changed files with 75 additions and 1 deletions

35
src/align.rs Normal file
View File

@ -0,0 +1,35 @@
//! Tools to control view alignment
pub struct Align {
pub h: HAlign,
pub v: VAlign,
}
impl Align {
pub fn new(h: HAlign, v: VAlign) -> Self {
Align {
h: h,
v: v,
}
}
pub fn top_left() -> Self {
Align::new(HAlign::Left, VAlign::Top)
}
pub fn center() -> Self {
Align::new(HAlign::Center, VAlign::Center)
}
}
pub enum HAlign {
Left,
Center,
Right,
}
pub enum VAlign {
Top,
Center,
Bottom,
}

View File

@ -28,6 +28,7 @@ pub mod view;
pub mod printer; pub mod printer;
pub mod vec; pub mod vec;
pub mod color; pub mod color;
pub mod align;
mod div; mod div;
mod utf8; mod utf8;

View File

@ -4,6 +4,7 @@ use vec::Vec2;
use view::{View,DimensionRequest,SizeRequest}; use view::{View,DimensionRequest,SizeRequest};
use div::*; use div::*;
use printer::Printer; use printer::Printer;
use align::*;
use event::*; use event::*;
use super::scroll::ScrollBase; use super::scroll::ScrollBase;
@ -12,6 +13,8 @@ pub struct TextView {
content: String, content: String,
rows: Vec<Row>, rows: Vec<Row>,
align: Align,
scrollbase: ScrollBase, scrollbase: ScrollBase,
} }
@ -56,9 +59,28 @@ impl TextView {
content: content.to_string(), content: content.to_string(),
rows: Vec::new(), rows: Vec::new(),
scrollbase: ScrollBase::new(), scrollbase: ScrollBase::new(),
align: Align::top_left(),
} }
} }
pub fn h_align(mut self, h: HAlign) -> Self {
self.align.h = h;
self
}
pub fn v_align(mut self, v: VAlign) -> Self {
self.align.v = v;
self
}
pub fn align(mut self, a: Align) -> Self {
self.align = a;
self
}
/// Replace the text in this view. /// Replace the text in this view.
pub fn set_content(&mut self, content: &str) { pub fn set_content(&mut self, content: &str) {
let content = strip_last_newline(content); let content = strip_last_newline(content);
@ -182,9 +204,25 @@ impl <'a> Iterator for LinesIterator<'a> {
impl View for TextView { impl View for TextView {
fn draw(&mut self, printer: &Printer) { fn draw(&mut self, printer: &Printer) {
let h = self.rows.len();
let offset = match self.align.v {
VAlign::Top => 0,
VAlign::Center => (printer.size.y - h)/2,
VAlign::Bottom => printer.size.y - h,
};
let printer = &printer.sub_printer(Vec2::new(0,offset), printer.size, true);
self.scrollbase.draw(printer, |printer, i| { self.scrollbase.draw(printer, |printer, i| {
let row = &self.rows[i]; let row = &self.rows[i];
printer.print((0,0), &self.content[row.start..row.end]); let text = &self.content[row.start..row.end];
let l = text.chars().count();
let x = match self.align.h {
HAlign::Left => 0,
HAlign::Center => (printer.size.x-l)/2,
HAlign::Right => printer.size.x-l,
};
printer.print((x,0), text);
}); });
} }