1use crate::{Color4f, ColorSpace, TileMode, scalar};
5use skia_bindings as sb;
6
7#[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 use skia_bindings as sb;
26
27 pub type InPremul = sb::SkGradient_Interpolation_InPremul;
29 variant_name!(InPremul::Yes);
30
31 pub type ColorSpace = sb::SkGradient_Interpolation_ColorSpace;
35 variant_name!(ColorSpace::HSL);
36
37 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 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#[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 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 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 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 pub fn colors(&self) -> &'a [Color4f] {
117 self.colors
118 }
119
120 pub fn positions(&self) -> Option<&'a [scalar]> {
122 self.pos
123 }
124
125 pub fn color_space(&self) -> Option<&ColorSpace> {
127 self.color_space.as_ref()
128 }
129
130 pub fn tile_mode(&self) -> TileMode {
132 self.tile_mode
133 }
134}
135
136#[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
166pub 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 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 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 #[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 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}