1
0
mirror of https://github.com/emilk/egui.git synced 2026-08-29 12:50:04 -04:00

eframe: capture a screenshot using Frame::request_screenshot

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>
This commit is contained in:
amfaber
2023-03-29 16:34:22 +02:00
committed by GitHub
parent 74d43bfa17
commit 870264b005
11 changed files with 384 additions and 73 deletions

View File

@@ -101,6 +101,54 @@ impl ColorImage {
Self { size, pixels }
}
pub fn from_rgba_premultiplied(size: [usize; 2], rgba: &[u8]) -> Self {
assert_eq!(size[0] * size[1] * 4, rgba.len());
let pixels = rgba
.chunks_exact(4)
.map(|p| Color32::from_rgba_premultiplied(p[0], p[1], p[2], p[3]))
.collect();
Self { size, pixels }
}
/// A view of the underlying data as `&[u8]`
pub fn as_raw(&self) -> &[u8] {
bytemuck::cast_slice(&self.pixels)
}
/// A view of the underlying data as `&mut [u8]`
pub fn as_raw_mut(&mut self) -> &mut [u8] {
bytemuck::cast_slice_mut(&mut self.pixels)
}
/// Create a new Image from a patch of the current image. This method is especially convenient for screenshotting a part of the app
/// since `region` can be interpreted as screen coordinates of the entire screenshot if `pixels_per_point` is provided for the native application.
/// The floats of [`emath::Rect`] are cast to usize, rounding them down in order to interpret them as indices to the image data.
///
/// Panics if `region.min.x > region.max.x || region.min.y > region.max.y`, or if a region larger than the image is passed.
pub fn region(&self, region: &emath::Rect, pixels_per_point: Option<f32>) -> Self {
let pixels_per_point = pixels_per_point.unwrap_or(1.0);
let min_x = (region.min.x * pixels_per_point) as usize;
let max_x = (region.max.x * pixels_per_point) as usize;
let min_y = (region.min.y * pixels_per_point) as usize;
let max_y = (region.max.y * pixels_per_point) as usize;
assert!(min_x <= max_x);
assert!(min_y <= max_y);
let width = max_x - min_x;
let height = max_y - min_y;
let mut output = Vec::with_capacity(width * height);
let row_stride = self.size[0];
for row in min_y..max_y {
output.extend_from_slice(
&self.pixels[row * row_stride + min_x..row * row_stride + max_x],
);
}
Self {
size: [width, height],
pixels: output,
}
}
/// Create a [`ColorImage`] from flat RGB data.
///
/// This is what you want to use after having loaded an image file (and if