Introduce dynamic opacity support for Image and Svg

This commit is contained in:
Héctor Ramón Jiménez 2024-05-03 13:25:58 +02:00
parent 38cf87cb45
commit fa9e1d96ea
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
18 changed files with 142 additions and 33 deletions

View file

@ -174,5 +174,6 @@ pub trait Renderer: crate::Renderer {
filter_method: FilterMethod, filter_method: FilterMethod,
bounds: Rectangle, bounds: Rectangle,
rotation: Radians, rotation: Radians,
opacity: f32,
); );
} }

View file

@ -173,6 +173,7 @@ impl image::Renderer for () {
_filter_method: image::FilterMethod, _filter_method: image::FilterMethod,
_bounds: Rectangle, _bounds: Rectangle,
_rotation: Radians, _rotation: Radians,
_opacity: f32,
) { ) {
} }
} }
@ -188,6 +189,7 @@ impl svg::Renderer for () {
_color: Option<Color>, _color: Option<Color>,
_bounds: Rectangle, _bounds: Rectangle,
_rotation: Radians, _rotation: Radians,
_opacity: f32,
) { ) {
} }
} }

View file

@ -101,5 +101,6 @@ pub trait Renderer: crate::Renderer {
color: Option<Color>, color: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
rotation: Radians, rotation: Radians,
opacity: f32,
); );
} }

View file

@ -17,6 +17,7 @@ pub fn main() -> iced::Result {
struct Image { struct Image {
width: f32, width: f32,
opacity: f32,
rotation: Rotation, rotation: Rotation,
content_fit: ContentFit, content_fit: ContentFit,
spin: bool, spin: bool,
@ -26,6 +27,7 @@ struct Image {
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
enum Message { enum Message {
WidthChanged(f32), WidthChanged(f32),
OpacityChanged(f32),
RotationStrategyChanged(RotationStrategy), RotationStrategyChanged(RotationStrategy),
RotationChanged(Degrees), RotationChanged(Degrees),
ContentFitChanged(ContentFit), ContentFitChanged(ContentFit),
@ -39,6 +41,9 @@ impl Image {
Message::WidthChanged(width) => { Message::WidthChanged(width) => {
self.width = width; self.width = width;
} }
Message::OpacityChanged(opacity) => {
self.opacity = opacity;
}
Message::RotationStrategyChanged(strategy) => { Message::RotationStrategyChanged(strategy) => {
self.rotation = match strategy { self.rotation = match strategy {
RotationStrategy::Floating => { RotationStrategy::Floating => {
@ -97,6 +102,7 @@ impl Image {
.width(self.width) .width(self.width)
.content_fit(self.content_fit) .content_fit(self.content_fit)
.rotation(self.rotation) .rotation(self.rotation)
.opacity(self.opacity)
) )
.explain(Color::WHITE), .explain(Color::WHITE),
"I am Ferris!" "I am Ferris!"
@ -117,14 +123,15 @@ impl Image {
Message::ContentFitChanged Message::ContentFitChanged
) )
.width(Length::Fill), .width(Length::Fill),
column![ with_value(
slider(100.0..=500.0, self.width, Message::WidthChanged), slider(100.0..=500.0, self.width, Message::WidthChanged),
text(format!("Width: {}px", self.width)) format!("Width: {}px", self.width)
.size(12) ),
.line_height(1.0) with_value(
] slider(0.0..=1.0, self.opacity, Message::OpacityChanged)
.spacing(2) .step(0.01),
.align_items(Alignment::Center) format!("Opacity: {:.2}", self.opacity)
)
] ]
.spacing(10) .spacing(10)
.align_items(Alignment::End); .align_items(Alignment::End);
@ -139,7 +146,7 @@ impl Image {
Message::RotationStrategyChanged, Message::RotationStrategyChanged,
) )
.width(Length::Fill), .width(Length::Fill),
column![ with_value(
row![ row![
slider( slider(
Degrees::RANGE, Degrees::RANGE,
@ -153,15 +160,8 @@ impl Image {
] ]
.spacing(10) .spacing(10)
.align_items(Alignment::Center), .align_items(Alignment::Center),
text(format!( format!("Rotation: {:.0}°", f32::from(self.rotation.degrees()))
"Rotation: {:.0}°", )
f32::from(self.rotation.degrees())
))
.size(12)
.line_height(1.0)
]
.spacing(2)
.align_items(Alignment::Center)
] ]
.spacing(10) .spacing(10)
.align_items(Alignment::End); .align_items(Alignment::End);
@ -176,6 +176,7 @@ impl Default for Image {
fn default() -> Self { fn default() -> Self {
Self { Self {
width: 300.0, width: 300.0,
opacity: 1.0,
rotation: Rotation::default(), rotation: Rotation::default(),
content_fit: ContentFit::default(), content_fit: ContentFit::default(),
spin: false, spin: false,
@ -198,3 +199,13 @@ impl std::fmt::Display for RotationStrategy {
}) })
} }
} }
fn with_value<'a>(
control: impl Into<Element<'a, Message>>,
value: String,
) -> Element<'a, Message> {
column![control.into(), text(value).size(12).line_height(1.0)]
.spacing(2)
.align_items(Alignment::Center)
.into()
}

View file

@ -18,8 +18,11 @@ pub enum Image {
/// The bounds of the image. /// The bounds of the image.
bounds: Rectangle, bounds: Rectangle,
/// The rotation of the image in radians /// The rotation of the image.
rotation: Radians, rotation: Radians,
/// The opacity of the image.
opacity: f32,
}, },
/// A vector image. /// A vector image.
Vector { Vector {
@ -32,8 +35,11 @@ pub enum Image {
/// The bounds of the image. /// The bounds of the image.
bounds: Rectangle, bounds: Rectangle,
/// The rotation of the image in radians /// The rotation of the image.
rotation: Radians, rotation: Radians,
/// The opacity of the image.
opacity: f32,
}, },
} }

View file

@ -155,11 +155,18 @@ where
filter_method: image::FilterMethod, filter_method: image::FilterMethod,
bounds: Rectangle, bounds: Rectangle,
rotation: Radians, rotation: Radians,
opacity: f32,
) { ) {
delegate!( delegate!(
self, self,
renderer, renderer,
renderer.draw_image(handle, filter_method, bounds, rotation) renderer.draw_image(
handle,
filter_method,
bounds,
rotation,
opacity
)
); );
} }
} }
@ -179,11 +186,12 @@ where
color: Option<Color>, color: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
rotation: Radians, rotation: Radians,
opacity: f32,
) { ) {
delegate!( delegate!(
self, self,
renderer, renderer,
renderer.draw_svg(handle, color, bounds, rotation) renderer.draw_svg(handle, color, bounds, rotation, opacity)
); );
} }
} }

View file

@ -551,6 +551,7 @@ impl Engine {
filter_method, filter_method,
bounds, bounds,
rotation, rotation,
opacity,
} => { } => {
let physical_bounds = *bounds * _transformation; let physical_bounds = *bounds * _transformation;
@ -574,6 +575,7 @@ impl Engine {
handle, handle,
*filter_method, *filter_method,
*bounds, *bounds,
*opacity,
_pixels, _pixels,
transform, transform,
clip_mask, clip_mask,
@ -585,6 +587,7 @@ impl Engine {
color, color,
bounds, bounds,
rotation, rotation,
opacity,
} => { } => {
let physical_bounds = *bounds * _transformation; let physical_bounds = *bounds * _transformation;
@ -608,6 +611,7 @@ impl Engine {
handle, handle,
*color, *color,
physical_bounds, physical_bounds,
*opacity,
_pixels, _pixels,
transform, transform,
clip_mask, clip_mask,

View file

@ -122,12 +122,14 @@ impl Layer {
bounds: Rectangle, bounds: Rectangle,
transformation: Transformation, transformation: Transformation,
rotation: Radians, rotation: Radians,
opacity: f32,
) { ) {
let image = Image::Raster { let image = Image::Raster {
handle, handle,
filter_method, filter_method,
bounds: bounds * transformation, bounds: bounds * transformation,
rotation, rotation,
opacity,
}; };
self.images.push(image); self.images.push(image);
@ -140,12 +142,14 @@ impl Layer {
bounds: Rectangle, bounds: Rectangle,
transformation: Transformation, transformation: Transformation,
rotation: Radians, rotation: Radians,
opacity: f32,
) { ) {
let svg = Image::Vector { let svg = Image::Vector {
handle, handle,
color, color,
bounds: bounds * transformation, bounds: bounds * transformation,
rotation, rotation,
opacity,
}; };
self.images.push(svg); self.images.push(svg);

View file

@ -378,6 +378,7 @@ impl core::image::Renderer for Renderer {
filter_method: core::image::FilterMethod, filter_method: core::image::FilterMethod,
bounds: Rectangle, bounds: Rectangle,
rotation: core::Radians, rotation: core::Radians,
opacity: f32,
) { ) {
let (layer, transformation) = self.layers.current_mut(); let (layer, transformation) = self.layers.current_mut();
layer.draw_image( layer.draw_image(
@ -386,6 +387,7 @@ impl core::image::Renderer for Renderer {
bounds, bounds,
transformation, transformation,
rotation, rotation,
opacity,
); );
} }
} }
@ -405,9 +407,17 @@ impl core::svg::Renderer for Renderer {
color: Option<Color>, color: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
rotation: core::Radians, rotation: core::Radians,
opacity: f32,
) { ) {
let (layer, transformation) = self.layers.current_mut(); let (layer, transformation) = self.layers.current_mut();
layer.draw_svg(handle, color, bounds, transformation, rotation); layer.draw_svg(
handle,
color,
bounds,
transformation,
rotation,
opacity,
);
} }
} }

View file

@ -31,6 +31,7 @@ impl Pipeline {
handle: &raster::Handle, handle: &raster::Handle,
filter_method: raster::FilterMethod, filter_method: raster::FilterMethod,
bounds: Rectangle, bounds: Rectangle,
opacity: f32,
pixels: &mut tiny_skia::PixmapMut<'_>, pixels: &mut tiny_skia::PixmapMut<'_>,
transform: tiny_skia::Transform, transform: tiny_skia::Transform,
clip_mask: Option<&tiny_skia::Mask>, clip_mask: Option<&tiny_skia::Mask>,
@ -56,6 +57,7 @@ impl Pipeline {
image, image,
&tiny_skia::PixmapPaint { &tiny_skia::PixmapPaint {
quality, quality,
opacity,
..Default::default() ..Default::default()
}, },
transform, transform,

View file

@ -34,6 +34,7 @@ impl Pipeline {
handle: &Handle, handle: &Handle,
color: Option<Color>, color: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
opacity: f32,
pixels: &mut tiny_skia::PixmapMut<'_>, pixels: &mut tiny_skia::PixmapMut<'_>,
transform: Transform, transform: Transform,
clip_mask: Option<&tiny_skia::Mask>, clip_mask: Option<&tiny_skia::Mask>,
@ -47,7 +48,10 @@ impl Pipeline {
bounds.x as i32, bounds.x as i32,
bounds.y as i32, bounds.y as i32,
image, image,
&tiny_skia::PixmapPaint::default(), &tiny_skia::PixmapPaint {
opacity,
..tiny_skia::PixmapPaint::default()
},
transform, transform,
clip_mask, clip_mask,
); );

View file

@ -137,16 +137,18 @@ impl Pipeline {
0 => Float32x2, 0 => Float32x2,
// Center // Center
1 => Float32x2, 1 => Float32x2,
// Image size // Scale
2 => Float32x2, 2 => Float32x2,
// Rotation // Rotation
3 => Float32, 3 => Float32,
// Opacity
4 => Float32,
// Atlas position // Atlas position
4 => Float32x2,
// Atlas scale
5 => Float32x2, 5 => Float32x2,
// Atlas scale
6 => Float32x2,
// Layer // Layer
6 => Sint32, 7 => Sint32,
), ),
}], }],
}, },
@ -229,6 +231,7 @@ impl Pipeline {
filter_method, filter_method,
bounds, bounds,
rotation, rotation,
opacity,
} => { } => {
if let Some(atlas_entry) = if let Some(atlas_entry) =
cache.upload_raster(device, encoder, handle) cache.upload_raster(device, encoder, handle)
@ -237,6 +240,7 @@ impl Pipeline {
[bounds.x, bounds.y], [bounds.x, bounds.y],
[bounds.width, bounds.height], [bounds.width, bounds.height],
f32::from(*rotation), f32::from(*rotation),
*opacity,
atlas_entry, atlas_entry,
match filter_method { match filter_method {
crate::core::image::FilterMethod::Nearest => { crate::core::image::FilterMethod::Nearest => {
@ -258,6 +262,7 @@ impl Pipeline {
color, color,
bounds, bounds,
rotation, rotation,
opacity,
} => { } => {
let size = [bounds.width, bounds.height]; let size = [bounds.width, bounds.height];
@ -268,6 +273,7 @@ impl Pipeline {
[bounds.x, bounds.y], [bounds.x, bounds.y],
size, size,
f32::from(*rotation), f32::from(*rotation),
*opacity,
atlas_entry, atlas_entry,
nearest_instances, nearest_instances,
); );
@ -498,6 +504,7 @@ struct Instance {
_center: [f32; 2], _center: [f32; 2],
_size: [f32; 2], _size: [f32; 2],
_rotation: f32, _rotation: f32,
_opacity: f32,
_position_in_atlas: [f32; 2], _position_in_atlas: [f32; 2],
_size_in_atlas: [f32; 2], _size_in_atlas: [f32; 2],
_layer: u32, _layer: u32,
@ -517,6 +524,7 @@ fn add_instances(
image_position: [f32; 2], image_position: [f32; 2],
image_size: [f32; 2], image_size: [f32; 2],
rotation: f32, rotation: f32,
opacity: f32,
entry: &atlas::Entry, entry: &atlas::Entry,
instances: &mut Vec<Instance>, instances: &mut Vec<Instance>,
) { ) {
@ -532,6 +540,7 @@ fn add_instances(
center, center,
image_size, image_size,
rotation, rotation,
opacity,
allocation, allocation,
instances, instances,
); );
@ -561,7 +570,8 @@ fn add_instances(
]; ];
add_instance( add_instance(
position, center, size, rotation, allocation, instances, position, center, size, rotation, opacity, allocation,
instances,
); );
} }
} }
@ -574,6 +584,7 @@ fn add_instance(
center: [f32; 2], center: [f32; 2],
size: [f32; 2], size: [f32; 2],
rotation: f32, rotation: f32,
opacity: f32,
allocation: &atlas::Allocation, allocation: &atlas::Allocation,
instances: &mut Vec<Instance>, instances: &mut Vec<Instance>,
) { ) {
@ -586,6 +597,7 @@ fn add_instance(
_center: center, _center: center,
_size: size, _size: size,
_rotation: rotation, _rotation: rotation,
_opacity: opacity,
_position_in_atlas: [ _position_in_atlas: [
(x as f32 + 0.5) / atlas::SIZE as f32, (x as f32 + 0.5) / atlas::SIZE as f32,
(y as f32 + 0.5) / atlas::SIZE as f32, (y as f32 + 0.5) / atlas::SIZE as f32,

View file

@ -119,12 +119,14 @@ impl Layer {
bounds: Rectangle, bounds: Rectangle,
transformation: Transformation, transformation: Transformation,
rotation: Radians, rotation: Radians,
opacity: f32,
) { ) {
let image = Image::Raster { let image = Image::Raster {
handle, handle,
filter_method, filter_method,
bounds: bounds * transformation, bounds: bounds * transformation,
rotation, rotation,
opacity,
}; };
self.images.push(image); self.images.push(image);
@ -137,12 +139,14 @@ impl Layer {
bounds: Rectangle, bounds: Rectangle,
transformation: Transformation, transformation: Transformation,
rotation: Radians, rotation: Radians,
opacity: f32,
) { ) {
let svg = Image::Vector { let svg = Image::Vector {
handle, handle,
color, color,
bounds: bounds * transformation, bounds: bounds * transformation,
rotation, rotation,
opacity,
}; };
self.images.push(svg); self.images.push(svg);

View file

@ -518,6 +518,7 @@ impl core::image::Renderer for Renderer {
filter_method: core::image::FilterMethod, filter_method: core::image::FilterMethod,
bounds: Rectangle, bounds: Rectangle,
rotation: core::Radians, rotation: core::Radians,
opacity: f32,
) { ) {
let (layer, transformation) = self.layers.current_mut(); let (layer, transformation) = self.layers.current_mut();
layer.draw_image( layer.draw_image(
@ -526,6 +527,7 @@ impl core::image::Renderer for Renderer {
bounds, bounds,
transformation, transformation,
rotation, rotation,
opacity,
); );
} }
} }
@ -542,9 +544,17 @@ impl core::svg::Renderer for Renderer {
color_filter: Option<Color>, color_filter: Option<Color>,
bounds: Rectangle, bounds: Rectangle,
rotation: core::Radians, rotation: core::Radians,
opacity: f32,
) { ) {
let (layer, transformation) = self.layers.current_mut(); let (layer, transformation) = self.layers.current_mut();
layer.draw_svg(handle, color_filter, bounds, transformation, rotation); layer.draw_svg(
handle,
color_filter,
bounds,
transformation,
rotation,
opacity,
);
} }
} }

View file

@ -12,15 +12,17 @@ struct VertexInput {
@location(1) center: vec2<f32>, @location(1) center: vec2<f32>,
@location(2) scale: vec2<f32>, @location(2) scale: vec2<f32>,
@location(3) rotation: f32, @location(3) rotation: f32,
@location(4) atlas_pos: vec2<f32>, @location(4) opacity: f32,
@location(5) atlas_scale: vec2<f32>, @location(5) atlas_pos: vec2<f32>,
@location(6) layer: i32, @location(6) atlas_scale: vec2<f32>,
@location(7) layer: i32,
} }
struct VertexOutput { struct VertexOutput {
@builtin(position) position: vec4<f32>, @builtin(position) position: vec4<f32>,
@location(0) uv: vec2<f32>, @location(0) uv: vec2<f32>,
@location(1) layer: f32, // this should be an i32, but naga currently reads that as requiring interpolation. @location(1) layer: f32, // this should be an i32, but naga currently reads that as requiring interpolation.
@location(2) opacity: f32,
} }
@vertex @vertex
@ -33,6 +35,7 @@ fn vs_main(input: VertexInput) -> VertexOutput {
// Map the vertex position to the atlas texture. // Map the vertex position to the atlas texture.
out.uv = vec2<f32>(v_pos * input.atlas_scale + input.atlas_pos); out.uv = vec2<f32>(v_pos * input.atlas_scale + input.atlas_pos);
out.layer = f32(input.layer); out.layer = f32(input.layer);
out.opacity = input.opacity;
// Calculate the vertex position and move the center to the origin // Calculate the vertex position and move the center to the origin
v_pos = input.pos + v_pos * input.scale - input.center; v_pos = input.pos + v_pos * input.scale - input.center;
@ -56,5 +59,5 @@ fn vs_main(input: VertexInput) -> VertexOutput {
@fragment @fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> { fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
// Sample the texture at the given UV coordinate and layer. // Sample the texture at the given UV coordinate and layer.
return textureSample(u_texture, u_sampler, input.uv, i32(input.layer)); return textureSample(u_texture, u_sampler, input.uv, i32(input.layer)) * vec4<f32>(1.0, 1.0, 1.0, input.opacity);
} }

View file

@ -38,6 +38,7 @@ pub struct Image<Handle> {
content_fit: ContentFit, content_fit: ContentFit,
filter_method: FilterMethod, filter_method: FilterMethod,
rotation: Rotation, rotation: Rotation,
opacity: f32,
} }
impl<Handle> Image<Handle> { impl<Handle> Image<Handle> {
@ -50,6 +51,7 @@ impl<Handle> Image<Handle> {
content_fit: ContentFit::default(), content_fit: ContentFit::default(),
filter_method: FilterMethod::default(), filter_method: FilterMethod::default(),
rotation: Rotation::default(), rotation: Rotation::default(),
opacity: 1.0,
} }
} }
@ -84,6 +86,15 @@ impl<Handle> Image<Handle> {
self.rotation = rotation.into(); self.rotation = rotation.into();
self self
} }
/// Sets the opacity of the [`Image`].
///
/// It should be in the [0.0, 1.0] range—`0.0` meaning completely transparent,
/// and `1.0` meaning completely opaque.
pub fn opacity(mut self, opacity: impl Into<f32>) -> Self {
self.opacity = opacity.into();
self
}
} }
/// Computes the layout of an [`Image`]. /// Computes the layout of an [`Image`].
@ -136,6 +147,7 @@ pub fn draw<Renderer, Handle>(
content_fit: ContentFit, content_fit: ContentFit,
filter_method: FilterMethod, filter_method: FilterMethod,
rotation: Rotation, rotation: Rotation,
opacity: f32,
) where ) where
Renderer: image::Renderer<Handle = Handle>, Renderer: image::Renderer<Handle = Handle>,
Handle: Clone, Handle: Clone,
@ -173,6 +185,7 @@ pub fn draw<Renderer, Handle>(
filter_method, filter_method,
drawing_bounds, drawing_bounds,
rotation.radians(), rotation.radians(),
opacity,
); );
}; };
@ -231,6 +244,7 @@ where
self.content_fit, self.content_fit,
self.filter_method, self.filter_method,
self.rotation, self.rotation,
self.opacity,
); );
} }
} }

View file

@ -342,6 +342,7 @@ where
..Rectangle::with_size(image_size) ..Rectangle::with_size(image_size)
}, },
Radians(0.0), Radians(0.0),
1.0,
); );
}); });
}); });

View file

@ -30,6 +30,7 @@ where
content_fit: ContentFit, content_fit: ContentFit,
class: Theme::Class<'a>, class: Theme::Class<'a>,
rotation: Rotation, rotation: Rotation,
opacity: f32,
} }
impl<'a, Theme> Svg<'a, Theme> impl<'a, Theme> Svg<'a, Theme>
@ -45,6 +46,7 @@ where
content_fit: ContentFit::Contain, content_fit: ContentFit::Contain,
class: Theme::default(), class: Theme::default(),
rotation: Rotation::default(), rotation: Rotation::default(),
opacity: 1.0,
} }
} }
@ -103,6 +105,15 @@ where
self.rotation = rotation.into(); self.rotation = rotation.into();
self self
} }
/// Sets the opacity of the [`Svg`].
///
/// It should be in the [0.0, 1.0] range—`0.0` meaning completely transparent,
/// and `1.0` meaning completely opaque.
pub fn opacity(mut self, opacity: impl Into<f32>) -> Self {
self.opacity = opacity.into();
self
}
} }
impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer> impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
@ -204,6 +215,7 @@ where
style.color, style.color,
drawing_bounds, drawing_bounds,
self.rotation.radians(), self.rotation.radians(),
self.opacity,
); );
}; };