Skip to main content

qr_code_styling/config/
gradient.rs

1//! Gradient configuration for QR code styling.
2
3use super::Color;
4use crate::types::GradientType;
5
6/// A color stop in a gradient.
7#[derive(Debug, Clone, PartialEq)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9pub struct ColorStop {
10    /// Position of the stop (0.0 to 1.0).
11    pub offset: f64,
12    /// Color at this stop.
13    pub color: Color,
14}
15
16impl ColorStop {
17    /// Create a new color stop.
18    pub fn new(offset: f64, color: Color) -> Self {
19        Self {
20            offset: offset.clamp(0.0, 1.0),
21            color,
22        }
23    }
24}
25
26/// Gradient definition for coloring QR code elements.
27#[derive(Debug, Clone, PartialEq)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29pub struct Gradient {
30    /// Type of gradient (linear or radial).
31    pub gradient_type: GradientType,
32    /// Rotation angle in radians (for linear gradients).
33    pub rotation: f64,
34    /// Color stops defining the gradient.
35    pub color_stops: Vec<ColorStop>,
36}
37
38impl Gradient {
39    /// Create a new linear gradient.
40    pub fn linear(color_stops: Vec<ColorStop>) -> Self {
41        Self {
42            gradient_type: GradientType::Linear,
43            rotation: 0.0,
44            color_stops,
45        }
46    }
47
48    /// Create a new linear gradient with rotation.
49    pub fn linear_rotated(rotation: f64, color_stops: Vec<ColorStop>) -> Self {
50        Self {
51            gradient_type: GradientType::Linear,
52            rotation,
53            color_stops,
54        }
55    }
56
57    /// Create a new radial gradient.
58    pub fn radial(color_stops: Vec<ColorStop>) -> Self {
59        Self {
60            gradient_type: GradientType::Radial,
61            rotation: 0.0,
62            color_stops,
63        }
64    }
65
66    /// Create a simple two-color linear gradient.
67    pub fn simple_linear(start: Color, end: Color) -> Self {
68        Self::linear(vec![
69            ColorStop::new(0.0, start),
70            ColorStop::new(1.0, end),
71        ])
72    }
73
74    /// Create a simple two-color radial gradient.
75    pub fn simple_radial(center: Color, edge: Color) -> Self {
76        Self::radial(vec![
77            ColorStop::new(0.0, center),
78            ColorStop::new(1.0, edge),
79        ])
80    }
81}
82
83impl Default for Gradient {
84    fn default() -> Self {
85        Self::simple_linear(Color::BLACK, Color::BLACK)
86    }
87}