63 lines
1.8 KiB
Rust
63 lines
1.8 KiB
Rust
use cosmic_text::{Family, Metrics};
|
|
|
|
use crate::prelude::*;
|
|
|
|
pub struct Text {
|
|
pub content: String,
|
|
pub attrs: TextAttrs,
|
|
buf: TextBuffer,
|
|
}
|
|
|
|
impl Text {
|
|
pub fn font_size(mut self, size: impl UiNum) -> Self {
|
|
self.attrs.font_size = size.to_f32();
|
|
self.attrs.line_height = self.attrs.font_size * 1.1;
|
|
self
|
|
}
|
|
pub fn color(mut self, color: UiColor) -> Self {
|
|
self.attrs.color = color;
|
|
self
|
|
}
|
|
pub fn family(mut self, family: Family<'static>) -> Self {
|
|
self.attrs.family = family;
|
|
self
|
|
}
|
|
pub fn line_height(mut self, height: f32) -> Self {
|
|
self.attrs.line_height = height;
|
|
self
|
|
}
|
|
pub fn new(content: impl Into<String>) -> Self {
|
|
let attrs = TextAttrs::default();
|
|
Self {
|
|
content: content.into(),
|
|
buf: TextBuffer::new_empty(Metrics::new(attrs.font_size, attrs.line_height)),
|
|
attrs,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Widget for Text {
|
|
fn draw(&mut self, painter: &mut Painter) {
|
|
let (handle, offset) = painter.render_text(&mut self.buf, &self.content, &self.attrs);
|
|
let dims = handle.size();
|
|
let size = offset.size(&handle);
|
|
let mut region = painter.region().center().expand(size);
|
|
region.top_left.offset += offset.top_left;
|
|
region.bot_right.offset = region.top_left.offset + dims;
|
|
painter.draw_texture_at(&handle, region);
|
|
// TODO: when on_update is added to painter,
|
|
// reuse TextureHandle
|
|
}
|
|
|
|
fn get_size(&mut self, ctx: &mut SizeCtx) -> Vec2 {
|
|
let (handle, offset) =
|
|
ctx.text
|
|
.draw(&mut self.buf, &self.content, &self.attrs, ctx.textures);
|
|
offset.size(&handle)
|
|
}
|
|
}
|
|
|
|
pub fn text(content: impl Into<String>) -> Text {
|
|
Text::new(content)
|
|
}
|