Remove Builder abstractions for gradients

This commit is contained in:
Héctor Ramón Jiménez 2023-05-19 03:32:21 +02:00
parent 6551a0b2ab
commit 4c1a082f04
No known key found for this signature in database
GPG key ID: 140CC052C94F138E
15 changed files with 167 additions and 213 deletions

View file

@ -1,4 +1,5 @@
use crate::{Color, Gradient}; use crate::gradient::{self, Gradient};
use crate::Color;
/// The background of some element. /// The background of some element.
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
@ -16,14 +17,14 @@ impl From<Color> for Background {
} }
} }
impl From<Color> for Option<Background> { impl From<Gradient> for Background {
fn from(color: Color) -> Self { fn from(gradient: Gradient) -> Self {
Some(Background::from(color)) Background::Gradient(gradient)
} }
} }
impl From<Gradient> for Option<Background> { impl From<gradient::Linear> for Background {
fn from(gradient: Gradient) -> Self { fn from(gradient: gradient::Linear) -> Self {
Some(Background::Gradient(gradient)) Background::Gradient(Gradient::Linear(gradient))
} }
} }

View file

@ -1,8 +1,8 @@
//! For creating a Gradient. //! Colors that transition progressively.
pub use linear::Linear;
use crate::{Color, Radians}; use crate::{Color, Radians};
use std::cmp::Ordering;
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
/// A fill which transitions colors progressively along a direction, either linearly, radially (TBD), /// A fill which transitions colors progressively along a direction, either linearly, radially (TBD),
/// or conically (TBD). /// or conically (TBD).
@ -14,19 +14,11 @@ pub enum Gradient {
} }
impl Gradient { impl Gradient {
/// Creates a new linear [`linear::Builder`].
///
/// This must be defined by an angle (in [`Degrees`] or [`Radians`])
/// which will use the bounds of the widget as a guide.
pub fn linear(angle: impl Into<Radians>) -> linear::Builder {
linear::Builder::new(angle.into())
}
/// Adjust the opacity of the gradient by a multiplier applied to each color stop. /// Adjust the opacity of the gradient by a multiplier applied to each color stop.
pub fn mul_alpha(mut self, alpha_multiplier: f32) -> Self { pub fn mul_alpha(mut self, alpha_multiplier: f32) -> Self {
match &mut self { match &mut self {
Gradient::Linear(linear) => { Gradient::Linear(linear) => {
for stop in linear.color_stops.iter_mut().flatten() { for stop in linear.stops.iter_mut().flatten() {
stop.color.a *= alpha_multiplier; stop.color.a *= alpha_multiplier;
} }
} }
@ -36,6 +28,12 @@ impl Gradient {
} }
} }
impl From<Linear> for Gradient {
fn from(gradient: Linear) -> Self {
Self::Linear(gradient)
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq)] #[derive(Debug, Default, Clone, Copy, PartialEq)]
/// A point along the gradient vector where the specified [`color`] is unmixed. /// A point along the gradient vector where the specified [`color`] is unmixed.
/// ///
@ -50,84 +48,58 @@ pub struct ColorStop {
pub color: Color, pub color: Color,
} }
pub mod linear { /// A linear gradient.
//! Linear gradient builder & definition. #[derive(Debug, Clone, Copy, PartialEq)]
use crate::gradient::{ColorStop, Gradient}; pub struct Linear {
use crate::{Color, Radians}; /// How the [`Gradient`] is angled within its bounds.
use std::cmp::Ordering; pub angle: Radians,
/// [`ColorStop`]s along the linear gradient path.
pub stops: [Option<ColorStop>; 8],
}
/// A linear gradient that can be used as a [`Background`]. impl Linear {
#[derive(Debug, Clone, Copy, PartialEq)] /// Creates a new [`Linear`] gradient with the given angle in [`Radians`].
pub struct Linear { pub fn new(angle: impl Into<Radians>) -> Self {
/// How the [`Gradient`] is angled within its bounds. Self {
pub angle: Radians, angle: angle.into(),
/// [`ColorStop`]s along the linear gradient path. stops: [None; 8],
pub color_stops: [Option<ColorStop>; 8], }
} }
/// A [`Linear`] builder. /// Adds a new [`ColorStop`], defined by an offset and a color, to the gradient.
#[derive(Debug)] ///
pub struct Builder { /// Any `offset` that is not within `0.0..=1.0` will be silently ignored.
angle: Radians, ///
stops: [Option<ColorStop>; 8], /// Any stop added after the 8th will be silently ignored.
pub fn add_stop(mut self, offset: f32, color: Color) -> Self {
if offset.is_finite() && (0.0..=1.0).contains(&offset) {
let (Ok(index) | Err(index)) =
self.stops.binary_search_by(|stop| match stop {
None => Ordering::Greater,
Some(stop) => stop.offset.partial_cmp(&offset).unwrap(),
});
if index < 8 {
self.stops[index] = Some(ColorStop { offset, color });
}
} else {
log::warn!("Gradient color stop must be within 0.0..=1.0 range.");
};
self
} }
impl Builder { /// Adds multiple [`ColorStop`]s to the gradient.
/// Creates a new [`Builder`]. ///
pub fn new(angle: Radians) -> Self { /// Any stop added after the 8th will be silently ignored.
Self { pub fn add_stops(
angle, mut self,
stops: [None; 8], stops: impl IntoIterator<Item = ColorStop>,
} ) -> Self {
for stop in stops.into_iter() {
self = self.add_stop(stop.offset, stop.color)
} }
/// Adds a new [`ColorStop`], defined by an offset and a color, to the gradient. self
///
/// Any `offset` that is not within `0.0..=1.0` will be silently ignored.
///
/// Any stop added after the 8th will be silently ignored.
pub fn add_stop(mut self, offset: f32, color: Color) -> Self {
if offset.is_finite() && (0.0..=1.0).contains(&offset) {
let (Ok(index) | Err(index)) =
self.stops.binary_search_by(|stop| match stop {
None => Ordering::Greater,
Some(stop) => stop.offset.partial_cmp(&offset).unwrap(),
});
if index < 8 {
self.stops[index] = Some(ColorStop { offset, color });
}
} else {
log::warn!(
"Gradient color stop must be within 0.0..=1.0 range."
);
};
self
}
/// Adds multiple [`ColorStop`]s to the gradient.
///
/// Any stop added after the 8th will be silently ignored.
pub fn add_stops(
mut self,
stops: impl IntoIterator<Item = ColorStop>,
) -> Self {
for stop in stops.into_iter() {
self = self.add_stop(stop.offset, stop.color)
}
self
}
/// Builds the linear [`Gradient`] of this [`Builder`].
///
/// Returns `BuilderError` if gradient in invalid.
pub fn build(self) -> Gradient {
Gradient::Linear(Linear {
angle: self.angle,
color_stops: self.stops,
})
}
} }
} }

View file

@ -10,8 +10,9 @@ use iced::application;
use iced::executor; use iced::executor;
use iced::theme::{self, Theme}; use iced::theme::{self, Theme};
use iced::widget::canvas; use iced::widget::canvas;
use iced::widget::canvas::gradient;
use iced::widget::canvas::stroke::{self, Stroke}; use iced::widget::canvas::stroke::{self, Stroke};
use iced::widget::canvas::{Cursor, Gradient, Path}; use iced::widget::canvas::{Cursor, Path};
use iced::window; use iced::window;
use iced::{ use iced::{
Application, Color, Command, Element, Length, Point, Rectangle, Renderer, Application, Color, Command, Element, Length, Point, Rectangle, Renderer,
@ -209,13 +210,12 @@ impl<Message> canvas::Program<Message> for State {
let earth = Path::circle(Point::ORIGIN, Self::EARTH_RADIUS); let earth = Path::circle(Point::ORIGIN, Self::EARTH_RADIUS);
let earth_fill = Gradient::linear( let earth_fill = gradient::Linear::new(
Point::new(-Self::EARTH_RADIUS, 0.0), Point::new(-Self::EARTH_RADIUS, 0.0),
Point::new(Self::EARTH_RADIUS, 0.0), Point::new(Self::EARTH_RADIUS, 0.0),
) )
.add_stop(0.2, Color::from_rgb(0.15, 0.50, 1.0)) .add_stop(0.2, Color::from_rgb(0.15, 0.50, 1.0))
.add_stop(0.8, Color::from_rgb(0.0, 0.20, 0.47)) .add_stop(0.8, Color::from_rgb(0.0, 0.20, 0.47));
.build();
frame.fill(&earth, earth_fill); frame.fill(&earth, earth_fill);

View file

@ -226,7 +226,7 @@ mod toast {
}; };
container::Appearance { container::Appearance {
background: pair.color.into(), background: Some(pair.color.into()),
text_color: pair.text.into(), text_color: pair.text.into(),
..Default::default() ..Default::default()
} }

View file

@ -1,3 +1,4 @@
use iced::gradient;
use iced::theme; use iced::theme;
use iced::theme::Palette; use iced::theme::Palette;
use iced::widget::{ use iced::widget::{
@ -7,8 +8,7 @@ use iced::widget::{
use iced::widget::{Button, Column, Container, Slider}; use iced::widget::{Button, Column, Container, Slider};
use iced::{alignment, widget, Theme}; use iced::{alignment, widget, Theme};
use iced::{ use iced::{
Color, Degrees, Element, Font, Gradient, Length, Radians, Renderer, Color, Degrees, Element, Font, Length, Radians, Renderer, Sandbox, Settings,
Sandbox, Settings,
}; };
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
@ -734,23 +734,25 @@ impl widget::button::StyleSheet for CustomButtonStyle {
fn active(&self, _style: &Self::Style) -> widget::button::Appearance { fn active(&self, _style: &Self::Style) -> widget::button::Appearance {
match self { match self {
CustomButtonStyle::Primary => widget::button::Appearance { CustomButtonStyle::Primary => widget::button::Appearance {
background: Gradient::linear(Degrees(270.0)) background: Some(
.add_stop(0.0, Palette::LIGHT.primary) gradient::Linear::new(Degrees(270.0))
.add_stop(1.0, Color::from_rgb8(54, 80, 168)) .add_stop(0.0, Palette::LIGHT.primary)
.build() .add_stop(1.0, Color::from_rgb8(54, 80, 168))
.into(), .into(),
),
text_color: Color::WHITE, text_color: Color::WHITE,
border_radius: 5.0, border_radius: 5.0,
..Default::default() ..Default::default()
}, },
CustomButtonStyle::Secondary => widget::button::Appearance { CustomButtonStyle::Secondary => widget::button::Appearance {
background: Gradient::linear(Radians( background: Some(
3.0 * std::f32::consts::PI / 2.0, gradient::Linear::new(Radians(
)) 3.0 * std::f32::consts::PI / 2.0,
.add_stop(0.0, Color::from_rgb8(194, 194, 194)) ))
.add_stop(1.0, Color::from_rgb8(126, 126, 126)) .add_stop(0.0, Color::from_rgb8(194, 194, 194))
.build() .add_stop(1.0, Color::from_rgb8(126, 126, 126))
.into(), .into(),
),
text_color: Color::WHITE, text_color: Color::WHITE,
border_radius: 5.0, border_radius: 5.0,
..Default::default() ..Default::default()

View file

@ -12,7 +12,7 @@ pub use stroke::{LineCap, LineDash, LineJoin, Stroke};
pub use style::Style; pub use style::Style;
pub use text::Text; pub use text::Text;
pub use crate::core::gradient::{self, Gradient}; pub use crate::gradient::{self, Gradient};
use crate::Primitive; use crate::Primitive;

View file

@ -1,8 +1,8 @@
//! Fill [crate::widget::canvas::Geometry] with a certain style. //! Fill [crate::widget::canvas::Geometry] with a certain style.
use iced_core::Color;
pub use crate::geometry::Style; pub use crate::geometry::Style;
use crate::Gradient;
use crate::core::Color;
use crate::gradient::{self, Gradient};
/// The style used to fill geometry. /// The style used to fill geometry.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -50,6 +50,15 @@ impl From<Gradient> for Fill {
} }
} }
impl From<gradient::Linear> for Fill {
fn from(gradient: gradient::Linear) -> Self {
Fill {
style: Style::Gradient(Gradient::Linear(gradient)),
..Default::default()
}
}
}
/// The fill rule defines how to determine what is inside and what is outside of /// The fill rule defines how to determine what is inside and what is outside of
/// a shape. /// a shape.
/// ///

View file

@ -1,10 +1,11 @@
//! A gradient that can be used as a [`Fill`] for a mesh. //! A gradient that can be used as a [`Fill`] for some geometry.
//! //!
//! For a gradient that you can use as a background variant for a widget, see [`Gradient`]. //! For a gradient that you can use as a background variant for a widget, see [`Gradient`].
//! //!
//! [`Gradient`]: crate::core::Gradient; //! [`Gradient`]: crate::core::Gradient;
use crate::core::Point; use crate::core::gradient::ColorStop;
pub use linear::Linear; use crate::core::{Color, Point};
use std::cmp::Ordering;
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
/// A fill which linearly interpolates colors along a direction. /// A fill which linearly interpolates colors along a direction.
@ -16,104 +17,72 @@ pub enum Gradient {
Linear(Linear), Linear(Linear),
} }
impl Gradient { impl From<Linear> for Gradient {
/// Creates a new linear [`linear::Builder`]. fn from(gradient: Linear) -> Self {
/// Self::Linear(gradient)
/// The `start` and `end` [`Point`]s define the absolute position of the [`Gradient`].
pub fn linear(start: Point, end: Point) -> linear::Builder {
linear::Builder::new(start, end)
} }
} }
pub mod linear { /// A linear gradient that can be used in the style of [`Fill`] or [`Stroke`].
//! Linear gradient builder & definition. ///
use crate::Gradient; /// [`Fill`]: crate::geometry::Fill;
use iced_core::gradient::ColorStop; /// [`Stroke`]: crate::geometry::Stroke;
use iced_core::{Color, Point}; #[derive(Debug, Clone, Copy, PartialEq)]
use std::cmp::Ordering; pub struct Linear {
/// The absolute starting position of the gradient.
pub start: Point,
/// A linear gradient that can be used in the style of [`Fill`] or [`Stroke`]. /// The absolute ending position of the gradient.
pub end: Point,
/// [`ColorStop`]s along the linear gradient direction.
pub stops: [Option<ColorStop>; 8],
}
impl Linear {
/// Creates a new [`Builder`].
pub fn new(start: Point, end: Point) -> Self {
Self {
start,
end,
stops: [None; 8],
}
}
/// Adds a new [`ColorStop`], defined by an offset and a color, to the gradient.
/// ///
/// [`Fill`]: crate::geometry::Fill; /// Any `offset` that is not within `0.0..=1.0` will be silently ignored.
/// [`Stroke`]: crate::geometry::Stroke; ///
#[derive(Debug, Clone, Copy, PartialEq)] /// Any stop added after the 8th will be silently ignored.
pub struct Linear { pub fn add_stop(mut self, offset: f32, color: Color) -> Self {
/// The absolute starting position of the gradient. if offset.is_finite() && (0.0..=1.0).contains(&offset) {
pub start: Point, let (Ok(index) | Err(index)) =
self.stops.binary_search_by(|stop| match stop {
None => Ordering::Greater,
Some(stop) => stop.offset.partial_cmp(&offset).unwrap(),
});
/// The absolute ending position of the gradient. if index < 8 {
pub end: Point, self.stops[index] = Some(ColorStop { offset, color });
}
} else {
log::warn!("Gradient: ColorStop must be within 0.0..=1.0 range.");
};
/// [`ColorStop`]s along the linear gradient direction. self
pub color_stops: [Option<ColorStop>; 8],
} }
/// A [`Linear`] builder. /// Adds multiple [`ColorStop`]s to the gradient.
#[derive(Debug)] ///
pub struct Builder { /// Any stop added after the 8th will be silently ignored.
start: Point, pub fn add_stops(
end: Point, mut self,
stops: [Option<ColorStop>; 8], stops: impl IntoIterator<Item = ColorStop>,
} ) -> Self {
for stop in stops.into_iter() {
impl Builder { self = self.add_stop(stop.offset, stop.color)
/// Creates a new [`Builder`].
pub fn new(start: Point, end: Point) -> Self {
Self {
start,
end,
stops: [None; 8],
}
} }
/// Adds a new [`ColorStop`], defined by an offset and a color, to the gradient. self
///
/// Any `offset` that is not within `0.0..=1.0` will be silently ignored.
///
/// Any stop added after the 8th will be silently ignored.
pub fn add_stop(mut self, offset: f32, color: Color) -> Self {
if offset.is_finite() && (0.0..=1.0).contains(&offset) {
let (Ok(index) | Err(index)) =
self.stops.binary_search_by(|stop| match stop {
None => Ordering::Greater,
Some(stop) => stop.offset.partial_cmp(&offset).unwrap(),
});
if index < 8 {
self.stops[index] = Some(ColorStop { offset, color });
}
} else {
log::warn!(
"Gradient: ColorStop must be within 0.0..=1.0 range."
);
};
self
}
/// Adds multiple [`ColorStop`]s to the gradient.
///
/// Any stop added after the 8th will be silently ignored.
pub fn add_stops(
mut self,
stops: impl IntoIterator<Item = ColorStop>,
) -> Self {
for stop in stops.into_iter() {
self = self.add_stop(stop.offset, stop.color)
}
self
}
/// Builds the linear [`Gradient`] of this [`Builder`].
///
/// Returns `BuilderError` if gradient in invalid.
pub fn build(self) -> Gradient {
Gradient::Linear(Linear {
start: self.start,
end: self.end,
color_stops: self.stops,
})
}
} }
} }

View file

@ -23,13 +23,13 @@
#![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(docsrs, feature(doc_cfg))]
mod antialiasing; mod antialiasing;
mod error; mod error;
mod gradient;
mod transformation; mod transformation;
mod viewport; mod viewport;
pub mod backend; pub mod backend;
pub mod compositor; pub mod compositor;
pub mod damage; pub mod damage;
pub mod gradient;
pub mod primitive; pub mod primitive;
pub mod renderer; pub mod renderer;

View file

@ -188,6 +188,7 @@ pub use style::theme;
pub use crate::core::alignment; pub use crate::core::alignment;
pub use crate::core::event; pub use crate::core::event;
pub use crate::core::gradient;
pub use crate::core::{ pub use crate::core::{
color, Alignment, Background, Color, ContentFit, Degrees, Gradient, Length, color, Alignment, Background, Color, ContentFit, Degrees, Gradient, Length,
Padding, Pixels, Point, Radians, Rectangle, Size, Vector, Padding, Pixels, Point, Radians, Rectangle, Size, Vector,

View file

@ -371,7 +371,7 @@ impl container::StyleSheet for Theme {
container::Appearance { container::Appearance {
text_color: None, text_color: None,
background: palette.background.weak.color.into(), background: Some(palette.background.weak.color.into()),
border_radius: 2.0, border_radius: 2.0,
border_width: 0.0, border_width: 0.0,
border_color: Color::TRANSPARENT, border_color: Color::TRANSPARENT,
@ -896,7 +896,7 @@ impl scrollable::StyleSheet for Theme {
let palette = self.extended_palette(); let palette = self.extended_palette();
scrollable::Scrollbar { scrollable::Scrollbar {
background: palette.background.weak.color.into(), background: Some(palette.background.weak.color.into()),
border_radius: 2.0, border_radius: 2.0,
border_width: 0.0, border_width: 0.0,
border_color: Color::TRANSPARENT, border_color: Color::TRANSPARENT,
@ -923,7 +923,7 @@ impl scrollable::StyleSheet for Theme {
let palette = self.extended_palette(); let palette = self.extended_palette();
scrollable::Scrollbar { scrollable::Scrollbar {
background: palette.background.weak.color.into(), background: Some(palette.background.weak.color.into()),
border_radius: 2.0, border_radius: 2.0,
border_width: 0.0, border_width: 0.0,
border_color: Color::TRANSPARENT, border_color: Color::TRANSPARENT,

View file

@ -463,7 +463,7 @@ fn into_gradient<'a>(
let Gradient::Linear(linear) = gradient; let Gradient::Linear(linear) = gradient;
let (start, end) = linear.angle.to_distance(&bounds); let (start, end) = linear.angle.to_distance(&bounds);
let stops: Vec<tiny_skia::GradientStop> = linear let stops: Vec<tiny_skia::GradientStop> = linear
.color_stops .stops
.into_iter() .into_iter()
.flatten() .flatten()
.map(|stop| { .map(|stop| {

View file

@ -233,7 +233,7 @@ pub fn into_paint(style: Style) -> tiny_skia::Paint<'static> {
Style::Gradient(gradient) => match gradient { Style::Gradient(gradient) => match gradient {
Gradient::Linear(linear) => { Gradient::Linear(linear) => {
let stops: Vec<tiny_skia::GradientStop> = linear let stops: Vec<tiny_skia::GradientStop> = linear
.color_stops .stops
.into_iter() .into_iter()
.flatten() .flatten()
.map(|stop| { .map(|stop| {

View file

@ -631,7 +631,7 @@ fn pack_gradient(gradient: &Gradient) -> [f32; 44] {
let mut pack: [f32; 44] = [0.0; 44]; let mut pack: [f32; 44] = [0.0; 44];
let mut offsets: [f32; 8] = [2.0; 8]; let mut offsets: [f32; 8] = [2.0; 8];
for (index, stop) in linear.color_stops.iter().enumerate() { for (index, stop) in linear.stops.iter().enumerate() {
let [r, g, b, a] = stop let [r, g, b, a] = stop
.map_or(crate::core::Color::default(), |s| s.color) .map_or(crate::core::Color::default(), |s| s.color)
.into_linear(); .into_linear();

View file

@ -317,7 +317,7 @@ fn pack_gradient(gradient: &core::Gradient, bounds: Rectangle) -> [f32; 44] {
core::Gradient::Linear(linear) => { core::Gradient::Linear(linear) => {
let mut pack: [f32; 44] = [0.0; 44]; let mut pack: [f32; 44] = [0.0; 44];
for (index, stop) in linear.color_stops.iter().enumerate() { for (index, stop) in linear.stops.iter().enumerate() {
let [r, g, b, a] = let [r, g, b, a] =
stop.map_or(Color::default(), |s| s.color).into_linear(); stop.map_or(Color::default(), |s| s.color).into_linear();