Skip to main content

cranpose_ui_graphics/
brush.rs

1//! Brush definitions for painting (solid colors, gradients, etc.)
2
3use std::sync::Arc;
4
5use crate::{
6    brush_sampler::BrushSampler, color::Color, geometry::Rect, point::Point,
7    render_effect::TileMode,
8};
9
10/// Describes how a shape, path or text is filled: a flat color or a gradient. Compose's `Brush`.
11#[derive(Clone, Debug, PartialEq)]
12pub enum Brush {
13    /// A single flat color. Compose's `SolidColor`.
14    Solid(Color),
15    /// Colors blend along the line from `start` to `end`. Compose's `Brush.linearGradient`.
16    LinearGradient {
17        /// Colors to blend between, in order, from `start` to `end`.
18        colors: Arc<[Color]>,
19        /// Positions of `colors` along the line from `start` to `end`, from 0.0 to 1.0; `None`
20        /// spaces the colors evenly.
21        stops: Option<Arc<[f32]>>,
22        /// Where the first color is reached, in logical pixels relative to the top-left corner of
23        /// the painted area. An infinite coordinate means the far edge of that area.
24        start: Point,
25        /// Where the last color is reached, in logical pixels relative to the top-left corner of
26        /// the painted area. An infinite coordinate means the far edge of that area.
27        end: Point,
28        /// How the gradient continues beyond `start` and `end`.
29        tile_mode: TileMode,
30    },
31    /// Colors blend with distance from `center`. Compose's `Brush.radialGradient`.
32    RadialGradient {
33        /// Colors to blend between, in order, from `center` outward.
34        colors: Arc<[Color]>,
35        /// Positions of `colors` from 0.0 to 1.0; `None` spaces the colors evenly.
36        stops: Option<Arc<[f32]>>,
37        /// Gradient center in logical pixels, relative to the top-left corner of the painted area.
38        center: Point,
39        /// Distance in logical pixels from `center` at which the last color is reached.
40        radius: f32,
41        /// How the gradient continues beyond `radius`.
42        tile_mode: TileMode,
43    },
44    /// Colors blend by angle around `center`, the first at 3 o'clock and the
45    /// rest clockwise from it. Compose's `Brush.sweepGradient`.
46    SweepGradient {
47        /// Colors to blend between, in order.
48        colors: Arc<[Color]>,
49        /// Positions of `colors` from 0.0 to 1.0; `None` spaces the colors evenly.
50        stops: Option<Arc<[f32]>>,
51        /// Gradient center in logical pixels, relative to the top-left corner of the painted area.
52        center: Point,
53    },
54}
55
56fn split_color_stops(color_stops: Vec<(f32, Color)>) -> (Vec<Color>, Vec<f32>) {
57    let mut colors = Vec::with_capacity(color_stops.len());
58    let mut stops = Vec::with_capacity(color_stops.len());
59    for (stop, color) in color_stops {
60        colors.push(color);
61        stops.push(stop);
62    }
63    (colors, stops)
64}
65
66/// A colour paints as a solid brush wherever a brush is taken, as Compose
67/// takes a `Color` beside each `Brush` overload.
68impl From<Color> for Brush {
69    fn from(color: Color) -> Self {
70        Self::Solid(color)
71    }
72}
73
74impl Brush {
75    /// Creates a brush that paints one flat color.
76    pub fn solid(color: Color) -> Self {
77        Self::Solid(color)
78    }
79
80    /// The brush's colours: its one colour, or a gradient's stops in order.
81    pub fn colors(&self) -> &[Color] {
82        match self {
83            Self::Solid(color) => std::slice::from_ref(color),
84            Self::LinearGradient { colors, .. }
85            | Self::RadialGradient { colors, .. }
86            | Self::SweepGradient { colors, .. } => colors,
87        }
88    }
89
90    /// The brush with each colour through `paint`. A gradient keeps its colour
91    /// list, shared, when `paint` leaves every colour's bits as they are.
92    pub fn map_colors(self, paint: impl Fn(Color) -> Color) -> Self {
93        let map = |colors: Arc<[Color]>| {
94            let bits = |color: Color| [color.0, color.1, color.2, color.3].map(f32::to_bits);
95            if colors
96                .iter()
97                .all(|&color| bits(paint(color)) == bits(color))
98            {
99                colors
100            } else {
101                colors.iter().map(|&color| paint(color)).collect()
102            }
103        };
104        match self {
105            Self::Solid(color) => Self::Solid(paint(color)),
106            Self::LinearGradient {
107                colors,
108                stops,
109                start,
110                end,
111                tile_mode,
112            } => Self::LinearGradient {
113                colors: map(colors),
114                stops,
115                start,
116                end,
117                tile_mode,
118            },
119            Self::RadialGradient {
120                colors,
121                stops,
122                center,
123                radius,
124                tile_mode,
125            } => Self::RadialGradient {
126                colors: map(colors),
127                stops,
128                center,
129                radius,
130                tile_mode,
131            },
132            Self::SweepGradient {
133                colors,
134                stops,
135                center,
136            } => Self::SweepGradient {
137                colors: map(colors),
138                stops,
139                center,
140            },
141        }
142    }
143
144    /// Whether the brush paints anything: some colour of it is not
145    /// transparent.
146    pub fn paints(&self) -> bool {
147        self.colors().iter().any(|color| color.3 > 0.0)
148    }
149
150    /// Creates a linear gradient that defaults to Compose semantics:
151    /// start at `(0,0)`, end at `(+inf,+inf)`, and `TileMode::Clamp`.
152    pub fn linear_gradient(colors: Vec<Color>) -> Self {
153        Self::linear_gradient_with_tile_mode(
154            colors,
155            Point { x: 0.0, y: 0.0 },
156            Point {
157                x: f32::INFINITY,
158                y: f32::INFINITY,
159            },
160            TileMode::Clamp,
161        )
162    }
163
164    /// Creates a linear gradient that spreads `colors` evenly from `start` to `end`, clamping
165    /// outside that line.
166    pub fn linear_gradient_range(colors: Vec<Color>, start: Point, end: Point) -> Self {
167        Self::linear_gradient_with_tile_mode(colors, start, end, TileMode::Clamp)
168    }
169
170    /// Creates a linear gradient that spreads `colors` evenly from `start` to `end`, repeating or
171    /// clamping outside that line as `tile_mode` says.
172    pub fn linear_gradient_with_tile_mode(
173        colors: Vec<Color>,
174        start: Point,
175        end: Point,
176        tile_mode: TileMode,
177    ) -> Self {
178        Self::LinearGradient {
179            colors: colors.into(),
180            stops: None,
181            start,
182            end,
183            tile_mode,
184        }
185    }
186
187    /// Creates a linear gradient from `(position, color)` pairs, with positions from 0.0 at `start`
188    /// to 1.0 at `end`.
189    pub fn linear_gradient_stops(
190        color_stops: Vec<(f32, Color)>,
191        start: Point,
192        end: Point,
193        tile_mode: TileMode,
194    ) -> Self {
195        let (colors, stops) = split_color_stops(color_stops);
196        Self::LinearGradient {
197            colors: colors.into(),
198            stops: Some(stops.into()),
199            start,
200            end,
201            tile_mode,
202        }
203    }
204
205    /// Creates a vertical gradient that spreads `colors` evenly from `start_y` to `end_y`, clamping
206    /// outside that range.
207    pub fn vertical_gradient(colors: Vec<Color>, start_y: f32, end_y: f32) -> Self {
208        Self::vertical_gradient_tiled(colors, start_y, end_y, TileMode::Clamp)
209    }
210
211    /// Creates a vertical gradient that spreads `colors` evenly from `start_y` to `end_y`,
212    /// repeating or clamping outside that range as `tile_mode` says.
213    pub fn vertical_gradient_tiled(
214        colors: Vec<Color>,
215        start_y: f32,
216        end_y: f32,
217        tile_mode: TileMode,
218    ) -> Self {
219        Self::linear_gradient_with_tile_mode(
220            colors,
221            Point { x: 0.0, y: start_y },
222            Point { x: 0.0, y: end_y },
223            tile_mode,
224        )
225    }
226
227    /// Creates a vertical gradient across the full height of the painted area, clamping at both
228    /// ends.
229    pub fn vertical_gradient_default(colors: Vec<Color>) -> Self {
230        Self::vertical_gradient_tiled(colors, 0.0, f32::INFINITY, TileMode::Clamp)
231    }
232
233    /// Creates a vertical gradient from `(position, color)` pairs, with positions from 0.0 at
234    /// `start_y` to 1.0 at `end_y`.
235    pub fn vertical_gradient_stops(
236        color_stops: Vec<(f32, Color)>,
237        start_y: f32,
238        end_y: f32,
239        tile_mode: TileMode,
240    ) -> Self {
241        Self::linear_gradient_stops(
242            color_stops,
243            Point { x: 0.0, y: start_y },
244            Point { x: 0.0, y: end_y },
245            tile_mode,
246        )
247    }
248
249    /// Creates a horizontal gradient that spreads `colors` evenly from `start_x` to `end_x`,
250    /// clamping outside that range.
251    pub fn horizontal_gradient(colors: Vec<Color>, start_x: f32, end_x: f32) -> Self {
252        Self::horizontal_gradient_tiled(colors, start_x, end_x, TileMode::Clamp)
253    }
254
255    /// Creates a horizontal gradient that spreads `colors` evenly from `start_x` to `end_x`,
256    /// repeating or clamping outside that range as `tile_mode` says.
257    pub fn horizontal_gradient_tiled(
258        colors: Vec<Color>,
259        start_x: f32,
260        end_x: f32,
261        tile_mode: TileMode,
262    ) -> Self {
263        Self::linear_gradient_with_tile_mode(
264            colors,
265            Point { x: start_x, y: 0.0 },
266            Point { x: end_x, y: 0.0 },
267            tile_mode,
268        )
269    }
270
271    /// Creates a horizontal gradient across the full width of the painted area, clamping at both
272    /// ends.
273    pub fn horizontal_gradient_default(colors: Vec<Color>) -> Self {
274        Self::horizontal_gradient_tiled(colors, 0.0, f32::INFINITY, TileMode::Clamp)
275    }
276
277    /// Creates a horizontal gradient from `(position, color)` pairs, with positions from 0.0 at
278    /// `start_x` to 1.0 at `end_x`.
279    pub fn horizontal_gradient_stops(
280        color_stops: Vec<(f32, Color)>,
281        start_x: f32,
282        end_x: f32,
283        tile_mode: TileMode,
284    ) -> Self {
285        Self::linear_gradient_stops(
286            color_stops,
287            Point { x: start_x, y: 0.0 },
288            Point { x: end_x, y: 0.0 },
289            tile_mode,
290        )
291    }
292
293    /// Creates a radial gradient that spreads `colors` evenly from `center` out to `radius`,
294    /// clamping beyond it.
295    pub fn radial_gradient(colors: Vec<Color>, center: Point, radius: f32) -> Self {
296        Self::radial_gradient_tiled(colors, center, radius, TileMode::Clamp)
297    }
298
299    /// Creates a radial gradient that spreads `colors` evenly from `center` out to `radius`,
300    /// repeating or clamping beyond it as `tile_mode` says.
301    pub fn radial_gradient_tiled(
302        colors: Vec<Color>,
303        center: Point,
304        radius: f32,
305        tile_mode: TileMode,
306    ) -> Self {
307        Self::RadialGradient {
308            colors: colors.into(),
309            stops: None,
310            center,
311            radius,
312            tile_mode,
313        }
314    }
315
316    /// Creates a radial gradient from `(position, color)` pairs, with positions from 0.0 at the
317    /// center to 1.0 at `radius`.
318    pub fn radial_gradient_stops(
319        color_stops: Vec<(f32, Color)>,
320        center: Point,
321        radius: f32,
322        tile_mode: TileMode,
323    ) -> Self {
324        let (colors, stops) = split_color_stops(color_stops);
325        Self::RadialGradient {
326            colors: colors.into(),
327            stops: Some(stops.into()),
328            center,
329            radius,
330            tile_mode,
331        }
332    }
333
334    /// Creates a sweep gradient that spreads `colors` evenly around `center`.
335    pub fn sweep_gradient(colors: Vec<Color>, center: Point) -> Self {
336        Self::SweepGradient {
337            colors: colors.into(),
338            stops: None,
339            center,
340        }
341    }
342
343    /// Creates a sweep gradient from `(position, color)` pairs, with positions from 0.0 to 1.0
344    /// around `center`.
345    pub fn sweep_gradient_stops(color_stops: Vec<(f32, Color)>, center: Point) -> Self {
346        let (colors, stops) = split_color_stops(color_stops);
347        Self::SweepGradient {
348            colors: colors.into(),
349            stops: Some(stops.into()),
350            center,
351        }
352    }
353
354    /// The color this brush paints at `point` when it fills `rect`, before
355    /// any dithering. Gradient coordinates are offsets from `rect`'s
356    /// top-left corner, and an infinite one is `rect`'s far edge. Where a
357    /// [`TileMode::Decal`] gradient paints nothing the color is transparent.
358    /// [`BrushSampler`] gives the same colors for many points of one rect.
359    pub fn color_at(&self, rect: Rect, point: Point) -> Color {
360        BrushSampler::new(self, rect).color_at(point)
361    }
362}
363
364#[cfg(test)]
365#[path = "tests/brush_tests.rs"]
366mod tests;