Files
iris/src/layout/text.rs
2025-08-24 20:34:19 -04:00

81 lines
2.1 KiB
Rust

use cosmic_text::{Attrs, Buffer, FontSystem, Metrics, Shaping, SwashCache};
use image::{Rgba, RgbaImage};
use crate::{
layout::{TextureHandle, Textures, UiColor},
util::HashMap,
};
pub(crate) struct TextData {
font_system: FontSystem,
swash_cache: SwashCache,
}
impl Default for TextData {
fn default() -> Self {
Self {
font_system: FontSystem::new(),
swash_cache: SwashCache::new(),
}
}
}
pub struct TextAttrs {
pub color: UiColor,
pub size: f32,
pub line_height: f32,
}
impl Default for TextAttrs {
fn default() -> Self {
let size = 14.0;
Self {
color: UiColor::WHITE,
size,
line_height: size * 1.2,
}
}
}
impl TextData {
pub fn draw(
&mut self,
content: &str,
attrs: &TextAttrs,
textures: &mut Textures,
) -> TextureHandle {
let metrics = Metrics::new(attrs.size, attrs.line_height);
let mut buffer = Buffer::new(&mut self.font_system, metrics);
let mut buffer = buffer.borrow_with(&mut self.font_system);
buffer.set_text(content, &Attrs::new(), Shaping::Advanced);
// dawg what is this api ???
let mut pixels = HashMap::new();
let mut min_x = 0;
let mut min_y = 0;
let mut max_x = 0;
let mut max_y = 0;
let c = attrs.color;
buffer.draw(
&mut self.swash_cache,
cosmic_text::Color::rgba(c.r, c.g, c.b, c.a),
|x, y, _, _, color| {
min_x = min_x.min(x);
min_y = min_y.min(y);
max_x = max_x.max(x);
max_y = max_y.max(y);
pixels.insert((x, y), Rgba(color.as_rgba()));
},
);
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);
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);
}
textures.add(image)
}
}