Lines
97.22 %
Functions
100 %
Branches
//! Halfblock cells from an RGBA image, keeping transparency as the pane's background.
use image::imageops::FilterType;
use image::{DynamicImage, Rgba, RgbaImage};
use ratatui::buffer::Buffer;
use ratatui::layout::{Rect, Size};
use ratatui::style::Color;
/// Pixels with less alpha than this show the background.
const OPAQUE_FROM: u8 = 128;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Half {
glyph: char,
fg: Option<Color>,
bg: Option<Color>,
}
pub struct Halves {
size: Size,
cells: Vec<Half>,
impl Halves {
/// One cell per two vertical pixels of `image` scaled to `size` cells by twice as many rows.
pub fn new(image: &DynamicImage, size: Size) -> Self {
let wide = premultiplied(image.to_rgba8());
let scaled = DynamicImage::ImageRgba8(wide)
.resize_exact(
u32::from(size.width),
u32::from(size.height) * 2,
FilterType::Triangle,
)
.to_rgba8();
let cells = (0..u32::from(size.height))
.flat_map(|row| (0..u32::from(size.width)).map(move |col| (col, row)))
.map(|(col, row)| {
half(
color(scaled.get_pixel(col, row * 2)),
color(scaled.get_pixel(col, row * 2 + 1)),
})
.collect();
Self { size, cells }
/// Draw into `area`, clipped to it.
/// Transparent pixels take `background`.
pub fn render(&self, area: Rect, buffer: &mut Buffer, background: Color) {
let width = usize::from(self.size.width);
for (index, half) in self.cells.iter().enumerate() {
let x = u16::try_from(index % width).unwrap_or(u16::MAX);
let y = u16::try_from(index / width).unwrap_or(u16::MAX);
if x >= area.width || y >= area.height {
continue;
if let Some(cell) = buffer.cell_mut((area.x + x, area.y + y)) {
cell.set_char(half.glyph)
.set_fg(half.fg.unwrap_or(background))
.set_bg(half.bg.unwrap_or(background));
/// Averaging colours of translucent pixels must not pull in their hidden RGB.
fn premultiplied(mut image: RgbaImage) -> RgbaImage {
for Rgba([r, g, b, a]) in image.pixels_mut() {
let scale = |channel: u8, alpha: u8| {
u8::try_from((u16::from(channel) * u16::from(alpha) + 127) / 255).unwrap_or(u8::MAX)
};
*r = scale(*r, *a);
*g = scale(*g, *a);
*b = scale(*b, *a);
image
/// The pixel's colour, un-premultiplied; `None` when it is transparent.
fn color(pixel: &Rgba<u8>) -> Option<Color> {
let Rgba([r, g, b, a]) = *pixel;
if a < OPAQUE_FROM {
return None;
let restore = |channel: u8| {
let alpha = u16::from(a);
u8::try_from((u16::from(channel) * 255 + alpha / 2) / alpha).unwrap_or(u8::MAX)
Some(Color::Rgb(restore(r), restore(g), restore(b)))
fn half(top: Option<Color>, bottom: Option<Color>) -> Half {
match (top, bottom) {
(Some(top), bottom) => Half {
glyph: '▀',
fg: Some(top),
bg: bottom,
},
(None, Some(bottom)) => Half {
glyph: '▄',
fg: Some(bottom),
bg: None,
(None, None) => Half {
glyph: ' ',
fg: None,