i_slint_core::graphics

Struct Image

Source
pub struct Image(/* private fields */);
Expand description

An image type that can be displayed by the Image element. You can construct Image objects from a path to an image file on disk, using Self::load_from_path.

Another typical use-case is to render the image content with Rust code. For this it’s most efficient to create a new SharedPixelBuffer with the known dimensions and pass the mutable slice to your rendering function. Afterwards you can create an Image.

The following example creates a 320x200 RGB pixel buffer and calls an external low_level_render() function to draw a shape into it. Finally the result is stored in an Image with Self::from_rgb8():


fn low_level_render(width: u32, height: u32, buffer: &mut [u8]) {
    // render beautiful circle or other shapes here
}

let mut pixel_buffer = SharedPixelBuffer::<Rgb8Pixel>::new(320, 200);

low_level_render(pixel_buffer.width(), pixel_buffer.height(),
                 pixel_buffer.make_mut_bytes());

let image = Image::from_rgb8(pixel_buffer);

Another use-case is to import existing image data into Slint, by creating a new Image through cloning of another image type.

The following example uses the popular image crate to load a .png file from disk, apply brightening filter on it and then import it into an Image:

let mut cat_image = image::open("cat.png").expect("Error loading cat image").into_rgba8();

image::imageops::colorops::brighten_in_place(&mut cat_image, 20);

let buffer = SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(
    cat_image.as_raw(),
    cat_image.width(),
    cat_image.height(),
);
let image = Image::from_rgba8(buffer);

A popular software (CPU) rendering library in Rust is tiny-skia. The following example shows how to use tiny-skia to render into a SharedPixelBuffer:

let mut pixel_buffer = SharedPixelBuffer::<Rgba8Pixel>::new(640, 480);
let width = pixel_buffer.width();
let height = pixel_buffer.height();
let mut pixmap = tiny_skia::PixmapMut::from_bytes(
    pixel_buffer.make_mut_bytes(), width, height
).unwrap();
pixmap.fill(tiny_skia::Color::TRANSPARENT);

let circle = tiny_skia::PathBuilder::from_circle(320., 240., 150.).unwrap();

let mut paint = tiny_skia::Paint::default();
paint.shader = tiny_skia::LinearGradient::new(
    tiny_skia::Point::from_xy(100.0, 100.0),
    tiny_skia::Point::from_xy(400.0, 400.0),
    vec![
        tiny_skia::GradientStop::new(0.0, tiny_skia::Color::from_rgba8(50, 127, 150, 200)),
        tiny_skia::GradientStop::new(1.0, tiny_skia::Color::from_rgba8(220, 140, 75, 180)),
    ],
    tiny_skia::SpreadMode::Pad,
    tiny_skia::Transform::identity(),
).unwrap();

pixmap.fill_path(&circle, &paint, tiny_skia::FillRule::Winding, Default::default(), None);

let image = Image::from_rgba8_premultiplied(pixel_buffer);

§Sending Image to a thread

Image is not Send, because it uses internal cache that are local to the Slint thread. If you want to create image data in a thread and send that to slint, construct the SharedPixelBuffer in a thread, and send that to Slint’s UI thread.

std::thread::spawn(move || {
    let mut pixel_buffer = SharedPixelBuffer::<Rgba8Pixel>::new(640, 480);
    // ... fill the pixel_buffer with data as shown in the previous example ...
    slint::invoke_from_event_loop(move || {
        // this will run in the Slint's UI thread
        let image = Image::from_rgba8_premultiplied(pixel_buffer);
        // ... use the image, eg:
        // my_ui_handle.upgrade().unwrap().set_image(image);
    });
});

Implementations§

Source§

impl Image

Source

pub fn load_from_path(path: &Path) -> Result<Self, LoadImageError>

Load an Image from a path to a file containing an image

Source

pub fn from_rgb8(buffer: SharedPixelBuffer<Rgb8Pixel>) -> Self

Creates a new Image from the specified shared pixel buffer, where each pixel has three color channels (red, green and blue) encoded as u8.

Source

pub fn from_rgba8(buffer: SharedPixelBuffer<Rgba8Pixel>) -> Self

Creates a new Image from the specified shared pixel buffer, where each pixel has four color channels (red, green, blue and alpha) encoded as u8.

Source

pub fn from_rgba8_premultiplied(buffer: SharedPixelBuffer<Rgba8Pixel>) -> Self

Creates a new Image from the specified shared pixel buffer, where each pixel has four color channels (red, green, blue and alpha) encoded as u8 and, in contrast to Self::from_rgba8, the alpha channel is also assumed to be multiplied to the red, green and blue channels.

Only construct an Image with this function if you know that your pixels are encoded this way.

Source

pub fn to_rgb8(&self) -> Option<SharedPixelBuffer<Rgb8Pixel>>

Returns the pixel buffer for the Image if available in RGB format without alpha. Returns None if the pixels cannot be obtained, for example when the image was created from borrowed OpenGL textures.

Source

pub fn to_rgba8(&self) -> Option<SharedPixelBuffer<Rgba8Pixel>>

Returns the pixel buffer for the Image if available in RGBA format. Returns None if the pixels cannot be obtained, for example when the image was created from borrowed OpenGL textures.

Source

pub fn to_rgba8_premultiplied(&self) -> Option<SharedPixelBuffer<Rgba8Pixel>>

Returns the pixel buffer for the Image if available in RGBA format, with the alpha channel pre-multiplied to the red, green, and blue channels. Returns None if the pixels cannot be obtained, for example when the image was created from borrowed OpenGL textures.

Source

pub unsafe fn from_borrowed_gl_2d_rgba_texture( texture_id: NonZeroU32, size: IntSize, ) -> Self

👎Deprecated since 1.2.0: Use BorrowedOpenGLTextureBuilder

Creates a new Image from an existing OpenGL texture. The texture remains borrowed by Slint for the duration of being used for rendering, such as when assigned as source property to an Image element. It’s the application’s responsibility to delete the texture when it is not used anymore.

The texture must be bindable against the GL_TEXTURE_2D target, have GL_RGBA as format for the pixel data.

When Slint renders the texture, it assumes that the origin of the texture is at the top-left. This is different from the default OpenGL coordinate system.

§Safety

This function is unsafe because invalid texture ids may lead to undefined behavior in OpenGL drivers. A valid texture id is one that was created by the same OpenGL context that is current during any of the invocations of the callback set on Window::set_rendering_notifier(). OpenGL contexts between instances of slint::Window are not sharing resources. Consequently slint::Image objects created from borrowed OpenGL textures cannot be shared between different windows.

Source

pub fn load_from_svg_data(buffer: &[u8]) -> Result<Self, LoadImageError>

Creates a new Image from the specified buffer, which contains SVG raw data.

Source

pub fn set_nine_slice_edges( &mut self, top: u16, right: u16, bottom: u16, left: u16, )

Sets the nine-slice edges of the image.

Nine-slice scaling is a method for scaling images in such a way that the corners are not distorted. The arguments define the pixel sizes of the edges that cut the image into 9 slices.

Source

pub fn size(&self) -> IntSize

Returns the size of the Image in pixels.

Source

pub fn path(&self) -> Option<&Path>

Returns the path of the image on disk, if it was constructed via Self::load_from_path.

For example:

let path_buf = Path::new(env!("CARGO_MANIFEST_DIR"))
    .join("../../demos/printerdemo/ui/images/cat.jpg");
let image = Image::load_from_path(&path_buf).unwrap();
assert_eq!(image.path(), Some(path_buf.as_path()));

Trait Implementations§

Source§

impl Clone for Image

Source§

fn clone(&self) -> Image

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Image

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Image

Source§

fn default() -> Image

Returns the “default value” for a type. Read more
Source§

impl<'a> From<&'a Image> for &'a ImageInner

Source§

fn from(other: &'a Image) -> Self

Converts to this type from the input type.
Source§

impl From<ImageInner> for Image

Source§

fn from(value: ImageInner) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for Image

Source§

fn eq(&self, other: &Image) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Image

Auto Trait Implementations§

§

impl Freeze for Image

§

impl !RefUnwindSafe for Image

§

impl !Send for Image

§

impl !Sync for Image

§

impl Unpin for Image

§

impl !UnwindSafe for Image

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.