initial text wrapping impl (resizing will break)

This commit is contained in:
2025-09-28 01:32:10 -04:00
parent b2950566af
commit 61df088cc7
8 changed files with 126 additions and 55 deletions

View File

@@ -26,11 +26,17 @@ pub struct TextAttrs {
pub font_size: f32,
pub line_height: f32,
pub family: Family<'static>,
pub wrap: bool,
}
impl TextAttrs {
pub fn apply(&self, font_system: &mut FontSystem, buf: &mut Buffer) {
buf.set_metrics(font_system, Metrics::new(self.font_size, self.line_height));
pub fn apply(&self, font_system: &mut FontSystem, buf: &mut Buffer, width: Option<f32>) {
buf.set_metrics_and_size(
font_system,
Metrics::new(self.font_size, self.line_height),
width,
None,
);
let attrs = Attrs::new().family(self.family);
let list = AttrsList::new(&attrs);
for line in &mut buf.lines {
@@ -49,6 +55,7 @@ impl Default for TextAttrs {
font_size: size,
line_height: size * 1.2,
family: Family::SansSerif,
wrap: false,
}
}
}
@@ -70,6 +77,7 @@ impl TextData {
cosmic_text::Color::rgba(c.r, c.g, c.b, c.a)
};
let mut max_width = 0.0f32;
let mut height = 0.0;
for run in buffer.layout_runs() {
for glyph in run.glyphs.iter() {
let physical_glyph = glyph.physical((0., 0.), 1.0);
@@ -95,22 +103,19 @@ impl TextData {
);
}
max_width = max_width.max(run.line_w);
height += run.line_height;
}
let width = (max_x - min_x + 1) as u32;
let height = (max_y - min_y + 1) as u32;
let mut image = RgbaImage::new(width, height);
let img_width = (max_x - min_x + 1) as u32;
let img_height = (max_y - min_y + 1) as u32;
let mut image = RgbaImage::new(img_width, img_height);
for ((x, y), color) in pixels {
let x = (x - min_x) as u32;
let y = (y - min_y) as u32;
image.put_pixel(x, y, color);
}
let lines = buffer.lines.len();
let offset = TextOffset {
top_left: Vec2::new(min_x as f32, min_y as f32),
bot_right: Vec2::new(
max_width - max_x as f32,
attrs.line_height * lines as f32 - max_y as f32,
),
bot_right: Vec2::new(max_width - max_x as f32, height - max_y as f32),
};
(textures.add(image), offset)
}