Skip to main content

skia_safe/effects/
gradient.rs

1//! Gradient specifications and shader factory functions for linear, radial, and two-point
2//! conical gradients.
3
4use crate::{Color4f, ColorSpace, TileMode, scalar};
5use skia_bindings as sb;
6
7/// Gradient interpolation settings.
8///
9/// Specifies how colors are interpolated in a gradient, including the color space
10/// and premultiplication mode.
11#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
12#[repr(C)]
13pub struct Interpolation {
14    pub in_premul: interpolation::InPremul,
15    pub color_space: interpolation::ColorSpace,
16    pub hue_method: interpolation::HueMethod,
17}
18
19native_transmutable!(sb::SkGradient_Interpolation, Interpolation);
20
21pub mod interpolation {
22    //! Types that specify how colors are interpolated in a gradient, including the
23    //! interpolation color space, premultiplication mode, and hue method.
24
25    use skia_bindings as sb;
26
27    /// Whether to interpolate colors in premultiplied alpha space.
28    pub type InPremul = sb::SkGradient_Interpolation_InPremul;
29    variant_name!(InPremul::Yes);
30
31    /// Color space for gradient interpolation.
32    ///
33    /// See <https://www.w3.org/TR/css-color-4/#interpolation-space>
34    pub type ColorSpace = sb::SkGradient_Interpolation_ColorSpace;
35    variant_name!(ColorSpace::HSL);
36
37    /// Hue interpolation method for cylindrical color spaces (LCH, OKLCH, HSL, HWB).
38    ///
39    /// See <https://www.w3.org/TR/css-color-4/#hue-interpolation>
40    pub type HueMethod = sb::SkGradient_Interpolation_HueMethod;
41    variant_name!(HueMethod::Shorter);
42}
43
44impl Default for Interpolation {
45    fn default() -> Self {
46        Self {
47            in_premul: interpolation::InPremul::No,
48            color_space: interpolation::ColorSpace::Destination,
49            hue_method: interpolation::HueMethod::Shorter,
50        }
51    }
52}
53
54impl Interpolation {
55    /// Create interpolation settings from legacy flags.
56    pub fn from_flags(flags: u32) -> Self {
57        Self {
58            in_premul: if flags & 1 != 0 {
59                interpolation::InPremul::Yes
60            } else {
61                interpolation::InPremul::No
62            },
63            color_space: interpolation::ColorSpace::Destination,
64            hue_method: interpolation::HueMethod::Shorter,
65        }
66    }
67}
68
69/// Specification for the colors in a gradient.
70///
71/// Holds color data, positions, tile mode, and color space for gradient construction.
72/// All references must outlive any shader created from it.
73#[derive(Debug, Clone)]
74pub struct Colors<'a> {
75    colors: &'a [Color4f],
76    pos: Option<&'a [scalar]>,
77    color_space: Option<ColorSpace>,
78    tile_mode: TileMode,
79}
80
81impl<'a> Colors<'a> {
82    /// Create gradient colors with explicit positions.
83    ///
84    /// - `colors` The colors for the gradient.
85    /// - `pos` Relative positions of each color (0.0 to 1.0). Must be strictly increasing.
86    ///          If `None`, colors are distributed evenly.
87    /// - `tile_mode` Tiling mode for the gradient.
88    /// - `color_space` Optional color space. If `None`, colors are treated as sRGB.
89    pub fn new(
90        colors: &'a [Color4f],
91        pos: Option<&'a [scalar]>,
92        tile_mode: TileMode,
93        color_space: impl Into<Option<ColorSpace>>,
94    ) -> Self {
95        // Validate positions match colors if provided
96        assert!(pos.is_none_or(|pos| pos.len() == colors.len()));
97
98        Self {
99            colors,
100            pos,
101            color_space: color_space.into(),
102            tile_mode,
103        }
104    }
105
106    /// Create gradient colors with evenly distributed positions.
107    pub fn new_evenly_spaced(
108        colors: &'a [Color4f],
109        tile_mode: TileMode,
110        color_space: impl Into<Option<ColorSpace>>,
111    ) -> Self {
112        Self::new(colors, None, tile_mode, color_space)
113    }
114
115    /// Returns a reference to the colors.
116    pub fn colors(&self) -> &'a [Color4f] {
117        self.colors
118    }
119
120    /// Returns a reference to the positions.
121    pub fn positions(&self) -> Option<&'a [scalar]> {
122        self.pos
123    }
124
125    /// Returns a reference to the color space.
126    pub fn color_space(&self) -> Option<&ColorSpace> {
127        self.color_space.as_ref()
128    }
129
130    /// Returns the tile mode.
131    pub fn tile_mode(&self) -> TileMode {
132        self.tile_mode
133    }
134}
135
136/// Gradient specification combining colors and interpolation settings.
137///
138/// This type corresponds to the C++ `SkGradient` class and encapsulates
139/// all parameters needed to define a gradient's appearance.
140///
141/// Note: This is a lightweight wrapper around [`Colors`] and [`Interpolation`].
142/// The actual C++ `SkGradient` object is constructed on-demand when creating shaders.
143#[derive(Debug, Clone)]
144pub struct Gradient<'a> {
145    colors: Colors<'a>,
146    interpolation: Interpolation,
147}
148
149impl<'a> Gradient<'a> {
150    pub fn new(colors: Colors<'a>, interpolation: impl Into<Interpolation>) -> Self {
151        Self {
152            colors,
153            interpolation: interpolation.into(),
154        }
155    }
156
157    pub fn colors(&self) -> &Colors<'a> {
158        &self.colors
159    }
160
161    pub fn interpolation(&self) -> &Interpolation {
162        &self.interpolation
163    }
164}
165
166/// Shader factory functions that accept [`Gradient`] parameters.
167///
168/// These functions correspond to the C++ `SkShaders` namespace gradient functions.
169pub mod shaders {
170    use super::{Gradient, scalar};
171    use crate::{Matrix, Point, Shader, prelude::*};
172    use skia_bindings as sb;
173    use std::ptr;
174
175    /// Returns a shader that generates a linear gradient between the two specified points.
176    ///
177    /// - `points` Array of 2 points, the end-points of the line segment
178    /// - `gradient` Description of the colors and interpolation method
179    /// - `local_matrix` Optional local matrix
180    pub fn linear_gradient<'a>(
181        points: (impl Into<Point>, impl Into<Point>),
182        gradient: &Gradient<'_>,
183        local_matrix: impl Into<Option<&'a Matrix>>,
184    ) -> Option<Shader> {
185        let points = [points.0.into(), points.1.into()];
186        let local_matrix = local_matrix.into();
187        let colors = gradient.colors();
188        let interpolation = gradient.interpolation();
189        let positions = colors.positions();
190        let color_space = colors.color_space().cloned();
191
192        Shader::from_ptr(unsafe {
193            sb::C_SkShaders_LinearGradient(
194                points.native().as_ptr(),
195                colors.colors().native().as_ptr(),
196                colors.colors().len(),
197                positions.map_or(ptr::null(), |pos| pos.as_ptr()),
198                positions.map_or(0, |pos| pos.len()),
199                colors.tile_mode(),
200                color_space.into_ptr_or_null(),
201                interpolation.native(),
202                local_matrix.native_ptr_or_null(),
203            )
204        })
205    }
206
207    /// Returns a shader that generates a radial gradient given the center and radius.
208    ///
209    /// - `center` The center of the circle for this gradient
210    /// - `radius` Must be positive. The radius of the circle for this gradient
211    /// - `gradient` Description of the colors and interpolation method
212    /// - `local_matrix` Optional local matrix
213    pub fn radial_gradient<'a>(
214        (center, radius): (impl Into<Point>, scalar),
215        gradient: &Gradient<'_>,
216        local_matrix: impl Into<Option<&'a Matrix>>,
217    ) -> Option<Shader> {
218        let center = center.into();
219        let local_matrix = local_matrix.into();
220        let colors = gradient.colors();
221        let interpolation = gradient.interpolation();
222        let positions = colors.positions();
223        let color_space = colors.color_space().cloned();
224
225        Shader::from_ptr(unsafe {
226            sb::C_SkShaders_RadialGradient(
227                center.native(),
228                radius,
229                colors.colors().native().as_ptr(),
230                colors.colors().len(),
231                positions.map_or(ptr::null(), |pos| pos.as_ptr()),
232                positions.map_or(0, |pos| pos.len()),
233                colors.tile_mode(),
234                color_space.into_ptr_or_null(),
235                interpolation.native(),
236                local_matrix.native_ptr_or_null(),
237            )
238        })
239    }
240
241    /// Returns a shader that generates a conical gradient given two circles.
242    ///
243    /// The gradient interprets the two circles according to the following HTML spec:
244    /// <http://dev.w3.org/html5/2dcontext/#dom-context-2d-createradialgradient>
245    ///
246    /// - `start` The center of the start circle
247    /// - `start_radius` Must be positive. The radius of the start circle
248    /// - `end` The center of the end circle
249    /// - `end_radius` Must be positive. The radius of the end circle
250    /// - `gradient` Description of the colors and interpolation method
251    /// - `local_matrix` Optional local matrix
252    #[allow(clippy::too_many_arguments)]
253    pub fn two_point_conical_gradient<'a>(
254        (start, start_radius): (impl Into<Point>, scalar),
255        (end, end_radius): (impl Into<Point>, scalar),
256        gradient: &Gradient<'_>,
257        local_matrix: impl Into<Option<&'a Matrix>>,
258    ) -> Option<Shader> {
259        let start = start.into();
260        let end = end.into();
261        let local_matrix = local_matrix.into();
262        let colors = gradient.colors();
263        let interpolation = gradient.interpolation();
264        let positions = colors.positions();
265        let color_space = colors.color_space().cloned();
266
267        Shader::from_ptr(unsafe {
268            sb::C_SkShaders_TwoPointConicalGradient(
269                start.native(),
270                start_radius,
271                end.native(),
272                end_radius,
273                colors.colors().native().as_ptr(),
274                colors.colors().len(),
275                positions.map_or(ptr::null(), |pos| pos.as_ptr()),
276                positions.map_or(0, |pos| pos.len()),
277                colors.tile_mode(),
278                color_space.into_ptr_or_null(),
279                interpolation.native(),
280                local_matrix.native_ptr_or_null(),
281            )
282        })
283    }
284
285    /// Returns a shader that generates a sweep gradient given a center.
286    ///
287    /// The shader accepts negative angles and angles larger than 360, draws between 0 and 360
288    /// degrees, similar to the CSS conic-gradient semantics. 0 degrees means horizontal
289    /// positive x axis. The start angle must be less than the end angle.
290    ///
291    /// - `center` The center of the sweep
292    /// - `start_angle` Start of the angular range, corresponding to pos == 0
293    /// - `end_angle` End of the angular range, corresponding to pos == 1
294    /// - `gradient` Description of the colors and interpolation method
295    /// - `local_matrix` Optional local matrix
296    pub fn sweep_gradient<'a>(
297        center: impl Into<Point>,
298        (start_angle, end_angle): (scalar, scalar),
299        gradient: &Gradient<'_>,
300        local_matrix: impl Into<Option<&'a Matrix>>,
301    ) -> Option<Shader> {
302        let center = center.into();
303        let local_matrix = local_matrix.into();
304        let colors = gradient.colors();
305        let interpolation = gradient.interpolation();
306        let positions = colors.positions();
307        let color_space = colors.color_space().cloned();
308
309        Shader::from_ptr(unsafe {
310            sb::C_SkShaders_SweepGradient(
311                center.native(),
312                start_angle,
313                end_angle,
314                colors.colors().native().as_ptr(),
315                colors.colors().len(),
316                positions.map_or(ptr::null(), |pos| pos.as_ptr()),
317                positions.map_or(0, |pos| pos.len()),
318                colors.tile_mode(),
319                color_space.into_ptr_or_null(),
320                interpolation.native(),
321                local_matrix.native_ptr_or_null(),
322            )
323        })
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330    use crate::{
331        Color, ColorSpace, Paint, Point, Rect, Shader,
332        prelude::{NativeAccess, RefCount},
333    };
334
335    #[test]
336    fn interpolation_from_flags() {
337        let interp_no_premul = Interpolation::from_flags(0);
338        assert_eq!(interp_no_premul.in_premul, interpolation::InPremul::No);
339
340        let interp_premul = Interpolation::from_flags(1);
341        assert_eq!(interp_premul.in_premul, interpolation::InPremul::Yes);
342    }
343
344    #[test]
345    #[should_panic]
346    fn colors_new_mismatched_positions() {
347        let colors = [Color::RED.into(), Color::BLUE.into()];
348        let positions = [0.0, 0.5, 1.0];
349        let _ = Colors::new(&colors, Some(&positions), TileMode::Clamp, None);
350    }
351
352    #[test]
353    fn linear_gradient_renders() {
354        let mut surface = crate::surfaces::raster_n32_premul((100, 100)).unwrap();
355        let canvas = surface.canvas();
356
357        let colors = [Color::RED.into(), Color::BLUE.into()];
358        let gradient_colors = Colors::new_evenly_spaced(&colors, TileMode::Clamp, None);
359        let gradient = Gradient::new(gradient_colors, Interpolation::default());
360
361        let shader = shaders::linear_gradient(
362            (Point::new(0.0, 0.0), Point::new(100.0, 0.0)),
363            &gradient,
364            None,
365        )
366        .unwrap();
367
368        let mut paint = Paint::default();
369        paint.set_shader(shader);
370
371        canvas.draw_rect(Rect::from_xywh(0.0, 0.0, 100.0, 100.0), &paint);
372
373        let image = surface.image_snapshot();
374        let pixel_left = image.peek_pixels().unwrap().get_color((10, 50));
375        let pixel_right = image.peek_pixels().unwrap().get_color((90, 50));
376
377        assert_ne!(pixel_left, pixel_right);
378        assert!(pixel_left.r() > pixel_right.r());
379        assert!(pixel_left.b() < pixel_right.b());
380    }
381
382    #[test]
383    fn linear_gradient_with_explicit_colorspace_keeps_refcount_balanced() {
384        assert_refcount_balanced(|gradient| {
385            shaders::linear_gradient(
386                (Point::new(0.0, 0.0), Point::new(100.0, 0.0)),
387                gradient,
388                None,
389            )
390        });
391    }
392
393    #[test]
394    fn radial_gradient_with_explicit_colorspace_keeps_refcount_balanced() {
395        assert_refcount_balanced(|gradient| {
396            shaders::radial_gradient((Point::new(50.0, 50.0), 25.0), gradient, None)
397        });
398    }
399
400    #[test]
401    fn two_point_conical_gradient_with_explicit_colorspace_keeps_refcount_balanced() {
402        assert_refcount_balanced(|gradient| {
403            shaders::two_point_conical_gradient(
404                (Point::new(25.0, 50.0), 10.0),
405                (Point::new(75.0, 50.0), 40.0),
406                gradient,
407                None,
408            )
409        });
410    }
411
412    #[test]
413    fn sweep_gradient_with_explicit_colorspace_keeps_refcount_balanced() {
414        assert_refcount_balanced(|gradient| {
415            shaders::sweep_gradient(Point::new(50.0, 50.0), (0.0, 360.0), gradient, None)
416        });
417    }
418
419    fn test_color_space() -> ColorSpace {
420        ColorSpace::new_srgb().with_color_spin()
421    }
422
423    fn assert_refcount_balanced(build_shader: impl FnOnce(&Gradient<'_>) -> Option<Shader>) {
424        let colors = [Color::RED.into(), Color::BLUE.into()];
425        let color_space = test_color_space();
426        let gradient_colors =
427            Colors::new_evenly_spaced(&colors, TileMode::Clamp, Some(color_space.clone()));
428        let gradient = Gradient::new(gradient_colors, Interpolation::default());
429
430        let ref_cnt_before = color_space.native().ref_cnt();
431        let shader = build_shader(&gradient).unwrap();
432        drop(shader);
433        let ref_cnt_after = color_space.native().ref_cnt();
434
435        assert_eq!(ref_cnt_after, ref_cnt_before);
436    }
437}