Skip to main content

skia_safe/core/
rrect.rs

1//! Describes a rounded rectangle with a bounds and a pair of radii for each corner. The bounds
2//! and radii can be set so that [`RRect`] describes: a rectangle with sharp corners; a circle; an
3//! oval; or a rectangle with one or more rounded corners.
4//!
5//! [`RRect`] allows implementing CSS properties that describe rounded corners. [`RRect`] may have
6//! up to eight different radii, one for each axis on each of its four corners.
7//!
8//! [`RRect`] may modify the provided parameters when initializing bounds and radii. If either axis
9//! radii is zero or less: radii are stored as zero; corner is square. If corner curves overlap,
10//! radii are proportionally reduced to fit within bounds.
11
12use crate::{Matrix, Point, Rect, Vector, interop, prelude::*, scalar};
13use skia_bindings::{self as sb, SkRRect};
14use std::{fmt, mem, ptr};
15
16/// Describes possible specializations of [`RRect`]. Each type is exclusive; an [`RRect`] may only
17/// have one type.
18///
19/// Type members become progressively less restrictive; larger values of type have more degrees of
20/// freedom than smaller values.
21pub use skia_bindings::SkRRect_Type as Type;
22variant_name!(Type::Complex);
23
24/// The radii are stored: top-left, top-right, bottom-right, bottom-left.
25pub use skia_bindings::SkRRect_Corner as Corner;
26variant_name!(Corner::LowerLeft);
27
28#[derive(Copy, Clone)]
29#[repr(transparent)]
30pub struct RRect(SkRRect);
31
32native_transmutable!(SkRRect, RRect);
33
34impl PartialEq for RRect {
35    fn eq(&self, rhs: &Self) -> bool {
36        unsafe { sb::C_SkRRect_Equals(self.native(), rhs.native()) }
37    }
38}
39
40impl Default for RRect {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46impl fmt::Debug for RRect {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.debug_struct("RRect")
49            .field("rect", &self.rect())
50            .field(
51                "radii",
52                &[
53                    self.radii(Corner::UpperLeft),
54                    self.radii(Corner::UpperRight),
55                    self.radii(Corner::LowerRight),
56                    self.radii(Corner::LowerLeft),
57                ],
58            )
59            .field("type", &self.get_type())
60            .finish()
61    }
62}
63
64impl AsRef<RRect> for RRect {
65    fn as_ref(&self) -> &RRect {
66        self
67    }
68}
69
70impl RRect {
71    /// Initializes bounds at (0, 0), the origin, with zero width and height. Initializes corner
72    /// radii to (0, 0), and sets the type to [`Type::Empty`].
73    pub fn new() -> Self {
74        RRect::construct(|rr| unsafe { sb::C_SkRRect_Construct(rr) })
75    }
76
77    pub fn get_type(&self) -> Type {
78        unsafe { sb::C_SkRRect_getType(self.native()) }
79    }
80
81    pub fn is_empty(&self) -> bool {
82        self.get_type() == Type::Empty
83    }
84
85    pub fn is_rect(&self) -> bool {
86        self.get_type() == Type::Rect
87    }
88
89    pub fn is_oval(&self) -> bool {
90        self.get_type() == Type::Oval
91    }
92
93    pub fn is_simple(&self) -> bool {
94        self.get_type() == Type::Simple
95    }
96
97    pub fn is_nine_patch(&self) -> bool {
98        self.get_type() == Type::NinePatch
99    }
100
101    pub fn is_complex(&self) -> bool {
102        self.get_type() == Type::Complex
103    }
104
105    /// Returns the span on the x-axis. This does not check if the result fits in a 32-bit float;
106    /// the result may be infinity.
107    pub fn width(&self) -> scalar {
108        self.rect().width()
109    }
110
111    /// Returns the span on the y-axis. This does not check if the result fits in a 32-bit float;
112    /// the result may be infinity.
113    pub fn height(&self) -> scalar {
114        self.rect().height()
115    }
116
117    /// Returns the top-left corner radii. If the type is [`Type::Empty`], [`Type::Rect`],
118    /// [`Type::Oval`], or [`Type::Simple`], returns a value representative of all corner radii. If
119    /// the type is [`Type::NinePatch`] or [`Type::Complex`], at least one of the remaining three
120    /// corners has a different value.
121    pub fn simple_radii(&self) -> Vector {
122        self.radii(Corner::UpperLeft)
123    }
124
125    /// Sets bounds to zero width and height at (0, 0), the origin. Sets corner radii to zero and
126    /// sets the type to [`Type::Empty`].
127    pub fn set_empty(&mut self) {
128        *self = Self::new()
129    }
130
131    /// Sets bounds to sorted `rect`, and sets corner radii to zero. If the set bounds has width and
132    /// height, sets the type to [`Type::Rect`]; otherwise, sets the type to [`Type::Empty`].
133    ///
134    /// - `rect` bounds to set
135    pub fn set_rect(&mut self, rect: impl AsRef<Rect>) {
136        unsafe { sb::C_SkRRect_setRect(self.native_mut(), rect.as_ref().native()) }
137    }
138
139    /// Initializes bounds at (0, 0), the origin, with zero width and height. Initializes corner
140    /// radii to (0, 0), and sets the type to [`Type::Empty`].
141    pub fn new_empty() -> Self {
142        Self::new()
143    }
144
145    // TODO: consider to rename all the following new_* function to from_* functions?
146    //       is it possible to find a proper convention here (new_ vs from_?)?
147
148    /// Initializes to a copy of `rect` bounds and zeroes corner radii.
149    ///
150    /// - `rect` bounds to copy
151    pub fn new_rect(rect: impl AsRef<Rect>) -> Self {
152        let mut rr = Self::default();
153        rr.set_rect(rect);
154        rr
155    }
156
157    /// Initializes to an oval, x-axis radii to half `oval.width()`, and all y-axis radii to half
158    /// `oval.height()`. If the oval bounds is empty, sets the type to [`Type::Empty`]. Otherwise,
159    /// sets the type to [`Type::Oval`].
160    ///
161    /// - `oval` bounds of oval
162    pub fn new_oval(oval: impl AsRef<Rect>) -> Self {
163        let mut rr = Self::default();
164        rr.set_oval(oval);
165        rr
166    }
167
168    /// Initializes to a rounded rectangle with the same radii for all four corners. If `rect` is
169    /// empty, sets the type to [`Type::Empty`]. Otherwise, if `x_rad` and `y_rad` are zero, sets
170    /// the type to [`Type::Rect`]. Otherwise, if `x_rad` is at least half `rect.width()` and
171    /// `y_rad` is at least half `rect.height()`, sets the type to [`Type::Oval`]. Otherwise, sets
172    /// the type to [`Type::Simple`].
173    ///
174    /// - `rect` bounds of rounded rectangle
175    /// - `x_rad` x-axis radius of corners
176    /// - `y_rad` y-axis radius of corners
177    pub fn new_rect_xy(rect: impl AsRef<Rect>, x_rad: scalar, y_rad: scalar) -> Self {
178        let mut rr = Self::default();
179        rr.set_rect_xy(rect.as_ref(), x_rad, y_rad);
180        rr
181    }
182
183    /// Initializes to a rounded rectangle with a radii array for individual control of all four
184    /// corners.
185    ///
186    /// If `rect` is empty, sets the type to [`Type::Empty`]. Otherwise, if one of each corner radii
187    /// are zero, sets the type to [`Type::Rect`]. Otherwise, if all x-axis radii are equal and at
188    /// least half `rect.width()`, and all y-axis radii are equal at least half `rect.height()`,
189    /// sets the type to [`Type::Oval`]. Otherwise, if all x-axis radii are equal, and all y-axis
190    /// radii are equal, sets the type to [`Type::Simple`]. Otherwise, sets the type to
191    /// [`Type::NinePatch`].
192    ///
193    /// - `rect` bounds of rounded rectangle
194    /// - `radii` corner x-axis and y-axis radii
195    pub fn new_rect_radii(rect: impl AsRef<Rect>, radii: &[Vector; 4]) -> Self {
196        let mut rr = Self::default();
197        rr.set_rect_radii(rect, radii);
198        rr
199    }
200
201    /// Initializes bounds to `rect`. Sets radii to (`left_rad`, `top_rad`), (`right_rad`,
202    /// `top_rad`), (`right_rad`, `bottom_rad`), (`left_rad`, `bottom_rad`).
203    ///
204    /// If `rect` is empty, sets the type to [`Type::Empty`]. Otherwise, if `left_rad` and
205    /// `right_rad` are zero, sets the type to [`Type::Rect`]. Otherwise, if `top_rad` and
206    /// `bottom_rad` are zero, sets the type to [`Type::Rect`]. Otherwise, if `left_rad` and
207    /// `right_rad` are equal and at least half `rect.width()`, and `top_rad` and `bottom_rad` are
208    /// equal at least half `rect.height()`, sets the type to [`Type::Oval`]. Otherwise, if
209    /// `left_rad` and `right_rad` are equal, and `top_rad` and `bottom_rad` are equal, sets the
210    /// type to [`Type::Simple`]. Otherwise, sets the type to [`Type::NinePatch`].
211    ///
212    /// Nine patch refers to the nine parts defined by the radii: one center rectangle, four edge
213    /// patches, and four corner patches.
214    ///
215    /// - `rect` bounds of rounded rectangle
216    /// - `left_rad` left-top and left-bottom x-axis radius
217    /// - `top_rad` left-top and right-top y-axis radius
218    /// - `right_rad` right-top and right-bottom x-axis radius
219    /// - `bottom_rad` left-bottom and right-bottom y-axis radius
220    pub fn new_nine_patch(
221        rect: impl AsRef<Rect>,
222        left_rad: scalar,
223        top_rad: scalar,
224        right_rad: scalar,
225        bottom_rad: scalar,
226    ) -> Self {
227        let mut r = Self::default();
228        r.set_nine_patch(rect, left_rad, top_rad, right_rad, bottom_rad);
229        r
230    }
231
232    /// Sets bounds to `oval`, x-axis radii to half `oval.width()`, and all y-axis radii to half
233    /// `oval.height()`. If the oval bounds is empty, sets the type to [`Type::Empty`]. Otherwise,
234    /// sets the type to [`Type::Oval`].
235    ///
236    /// - `oval` bounds of oval
237    pub fn set_oval(&mut self, oval: impl AsRef<Rect>) {
238        unsafe { self.native_mut().setOval(oval.as_ref().native()) }
239    }
240
241    /// Sets to a rounded rectangle with the same radii for all four corners. If `rect` is empty,
242    /// sets the type to [`Type::Empty`]. Otherwise, if `x_rad` or `y_rad` is zero, sets the type to
243    /// [`Type::Rect`]. Otherwise, if `x_rad` is at least half `rect.width()` and `y_rad` is at
244    /// least half `rect.height()`, sets the type to [`Type::Oval`]. Otherwise, sets the type to
245    /// [`Type::Simple`].
246    ///
247    /// - `rect` bounds of rounded rectangle
248    /// - `x_rad` x-axis radius of corners
249    /// - `y_rad` y-axis radius of corners
250    ///
251    /// Example (C++): <https://fiddle.skia.org/c/@RRect_setRectXY>
252    pub fn set_rect_xy(&mut self, rect: impl AsRef<Rect>, x_rad: scalar, y_rad: scalar) {
253        unsafe {
254            self.native_mut()
255                .setRectXY(rect.as_ref().native(), x_rad, y_rad)
256        }
257    }
258
259    /// Sets bounds to `rect`. Sets radii to (`left_rad`, `top_rad`), (`right_rad`, `top_rad`),
260    /// (`right_rad`, `bottom_rad`), (`left_rad`, `bottom_rad`).
261    ///
262    /// If `rect` is empty, sets the type to [`Type::Empty`]. Otherwise, if `left_rad` and
263    /// `right_rad` are zero, sets the type to [`Type::Rect`]. Otherwise, if `top_rad` and
264    /// `bottom_rad` are zero, sets the type to [`Type::Rect`]. Otherwise, if `left_rad` and
265    /// `right_rad` are equal and at least half `rect.width()`, and `top_rad` and `bottom_rad` are
266    /// equal at least half `rect.height()`, sets the type to [`Type::Oval`]. Otherwise, if
267    /// `left_rad` and `right_rad` are equal, and `top_rad` and `bottom_rad` are equal, sets the
268    /// type to [`Type::Simple`]. Otherwise, sets the type to [`Type::NinePatch`].
269    ///
270    /// Nine patch refers to the nine parts defined by the radii: one center rectangle, four edge
271    /// patches, and four corner patches.
272    ///
273    /// - `rect` bounds of rounded rectangle
274    /// - `left_rad` left-top and left-bottom x-axis radius
275    /// - `top_rad` left-top and right-top y-axis radius
276    /// - `right_rad` right-top and right-bottom x-axis radius
277    /// - `bottom_rad` left-bottom and right-bottom y-axis radius
278    pub fn set_nine_patch(
279        &mut self,
280        rect: impl AsRef<Rect>,
281        left_rad: scalar,
282        top_rad: scalar,
283        right_rad: scalar,
284        bottom_rad: scalar,
285    ) {
286        unsafe {
287            self.native_mut().setNinePatch(
288                rect.as_ref().native(),
289                left_rad,
290                top_rad,
291                right_rad,
292                bottom_rad,
293            )
294        }
295    }
296
297    /// Sets bounds to `rect`. Sets the radii array for individual control of all four corners.
298    ///
299    /// If `rect` is empty, sets the type to [`Type::Empty`]. Otherwise, if one of each corner radii
300    /// are zero, sets the type to [`Type::Rect`]. Otherwise, if all x-axis radii are equal and at
301    /// least half `rect.width()`, and all y-axis radii are equal at least half `rect.height()`,
302    /// sets the type to [`Type::Oval`]. Otherwise, if all x-axis radii are equal, and all y-axis
303    /// radii are equal, sets the type to [`Type::Simple`]. Otherwise, sets the type to
304    /// [`Type::NinePatch`].
305    ///
306    /// - `rect` bounds of rounded rectangle
307    /// - `radii` corner x-axis and y-axis radii
308    ///
309    /// Example (C++): <https://fiddle.skia.org/c/@RRect_setRectRadii>
310    /// Example (C++): <https://fiddle.skia.org/c/@RRect_setRectRadii>
311    pub fn set_rect_radii(&mut self, rect: impl AsRef<Rect>, radii: &[Vector; 4]) {
312        unsafe {
313            self.native_mut()
314                .setRectRadii(rect.as_ref().native(), radii.native().as_ptr())
315        }
316    }
317
318    /// Returns bounds. Bounds may have zero width or zero height. Bounds right is greater than or
319    /// equal to left; bounds bottom is greater than or equal to top. Result is identical to
320    /// [`Self::bounds()`].
321    pub fn rect(&self) -> &Rect {
322        Rect::from_native_ref(&self.native().fRect)
323    }
324
325    /// Returns the scalar pair for the radius of the curve on the x-axis and y-axis for one corner.
326    /// Both radii may be zero. If not zero, both are positive and finite.
327    ///
328    /// - `corner` corner to return radii for
329    pub fn radii(&self, corner: Corner) -> Vector {
330        Vector::from_native_c(self.native().fRadii[corner as usize])
331    }
332
333    /// Returns the corner radii for all four corners, in the same order as [`Corner`].
334    pub fn radii_ref(&self) -> &[Vector; 4] {
335        Vector::from_native_array_ref(&self.native().fRadii)
336    }
337
338    /// Returns bounds. Bounds may have zero width or zero height. Bounds right is greater than or
339    /// equal to left; bounds bottom is greater than or equal to top. Result is identical to
340    /// [`Self::rect()`].
341    pub fn bounds(&self) -> &Rect {
342        self.rect()
343    }
344
345    /// Insets bounds by `delta`, and adjusts radii by `delta`. `delta` may be positive, negative,
346    /// or zero.
347    ///
348    /// If either corner radius is zero, the corner has no curvature and is unchanged. Otherwise, if
349    /// the adjusted radius becomes negative, pins the radius to zero. If `delta.x` exceeds half the
350    /// bounds width, the bounds left and right are set to the bounds x-axis center. If `delta.y`
351    /// exceeds half the bounds height, the bounds top and bottom are set to the bounds y-axis
352    /// center.
353    ///
354    /// If `delta` causes the bounds to become infinite, the bounds is zeroed.
355    ///
356    /// Example (C++): <https://fiddle.skia.org/c/@RRect_inset>
357    pub fn inset(&mut self, delta: impl Into<Vector>) {
358        *self = self.with_inset(delta)
359    }
360
361    /// Copies this rounded rectangle to a new one, then insets the new bounds by `delta`, and
362    /// adjusts the new radii by `delta`. `delta` may be positive, negative, or zero.
363    ///
364    /// If either corner radius is zero, the corner has no curvature and is unchanged. Otherwise, if
365    /// the adjusted radius becomes negative, pins the radius to zero. If `delta.x` exceeds half the
366    /// new bounds width, the new bounds left and right are set to the new bounds x-axis center. If
367    /// `delta.y` exceeds half the new bounds height, the new bounds top and bottom are set to the
368    /// new bounds y-axis center.
369    ///
370    /// If `delta` causes the new bounds to become infinite, the new bounds is zeroed.
371    #[must_use]
372    pub fn with_inset(&self, delta: impl Into<Vector>) -> Self {
373        let delta = delta.into();
374        let mut r = Self::default();
375        unsafe { self.native().inset(delta.x, delta.y, r.native_mut()) };
376        r
377    }
378
379    /// Outsets bounds by `delta`, and adjusts radii by `delta`. `delta` may be positive, negative,
380    /// or zero.
381    ///
382    /// If either corner radius is zero, the corner has no curvature and is unchanged. Otherwise, if
383    /// the adjusted radius becomes negative, pins the radius to zero. If `delta.x` exceeds half the
384    /// bounds width, the bounds left and right are set to the bounds x-axis center. If `delta.y`
385    /// exceeds half the bounds height, the bounds top and bottom are set to the bounds y-axis
386    /// center.
387    ///
388    /// If `delta` causes the bounds to become infinite, the bounds is zeroed.
389    pub fn outset(&mut self, delta: impl Into<Vector>) {
390        *self = self.with_outset(delta)
391    }
392
393    /// Copies this rounded rectangle to a new one, then outsets the new bounds by `delta`, and
394    /// adjusts the new radii by `delta`. `delta` may be positive, negative, or zero.
395    ///
396    /// If either corner radius is zero, the corner has no curvature and is unchanged. Otherwise, if
397    /// the adjusted radius becomes negative, pins the radius to zero. If `delta.x` exceeds half the
398    /// new bounds width, the new bounds left and right are set to the new bounds x-axis center. If
399    /// `delta.y` exceeds half the new bounds height, the new bounds top and bottom are set to the
400    /// new bounds y-axis center.
401    ///
402    /// If `delta` causes the new bounds to become infinite, the new bounds is zeroed.
403    #[must_use]
404    pub fn with_outset(&self, delta: impl Into<Vector>) -> Self {
405        self.with_inset(-delta.into())
406    }
407
408    /// Translates this rounded rectangle by `delta`.
409    pub fn offset(&mut self, delta: impl Into<Vector>) {
410        Rect::from_native_ref_mut(&mut self.native_mut().fRect).offset(delta)
411    }
412
413    /// Returns this rounded rectangle translated by `delta`, with unchanged corner radii.
414    #[must_use]
415    pub fn with_offset(&self, delta: impl Into<Vector>) -> Self {
416        let mut copied = *self;
417        copied.offset(delta);
418        copied
419    }
420
421    /// Returns true if `point` is inside the bounds and corner radii, and if this rounded rectangle
422    /// is not empty.
423    pub fn contains_point(&self, point: impl Into<Point>) -> bool {
424        let point = point.into();
425        unsafe { sb::C_SkRRect_containsPoint(self.native(), point.native()) }
426    }
427
428    /// Returns true if `rect` is inside the bounds and corner radii, and if this rounded rectangle
429    /// and `rect` are not empty.
430    ///
431    /// - `rect` area tested for containment
432    ///
433    /// Example (C++): <https://fiddle.skia.org/c/@RRect_contains>
434    pub fn contains(&self, rect: impl AsRef<Rect>) -> bool {
435        unsafe { sb::C_SkRRect_containsRect(self.native(), rect.as_ref().native()) }
436    }
437
438    /// Returns true if the bounds and radii values are finite and describe a [`RRect`] type that
439    /// matches [`Self::get_type()`]. All [`RRect`] methods construct valid types, even if the input
440    /// values are not valid. Invalid [`RRect`] data can only be generated by corrupting memory.
441    ///
442    /// Example (C++): <https://fiddle.skia.org/c/@RRect_isValid>
443    pub fn is_valid(&self) -> bool {
444        unsafe { self.native().isValid() }
445    }
446
447    pub const SIZE_IN_MEMORY: usize = mem::size_of::<Self>();
448
449    /// Writes this rounded rectangle to `buffer`. Writes [`Self::SIZE_IN_MEMORY`] bytes, and
450    /// returns [`Self::SIZE_IN_MEMORY`], the number of bytes written.
451    ///
452    /// - `buffer` storage for this rounded rectangle
453    ///
454    /// Example (C++): <https://fiddle.skia.org/c/@RRect_writeToMemory>
455    pub fn write_to_memory(&self, buffer: &mut Vec<u8>) {
456        unsafe {
457            let size = self.native().writeToMemory(ptr::null_mut());
458            buffer.resize(size, 0);
459            let written = self.native().writeToMemory(buffer.as_mut_ptr() as _);
460            debug_assert_eq!(written, size);
461        }
462    }
463
464    /// Reads this rounded rectangle from `buffer`, reading [`Self::SIZE_IN_MEMORY`] bytes. Returns
465    /// [`Self::SIZE_IN_MEMORY`], the bytes read, if `buffer.len()` is at least
466    /// [`Self::SIZE_IN_MEMORY`]. Otherwise, returns zero.
467    ///
468    /// - `buffer` memory to read from
469    ///
470    /// Example (C++): <https://fiddle.skia.org/c/@RRect_readFromMemory>
471    pub fn read_from_memory(&mut self, buffer: &[u8]) -> usize {
472        unsafe {
473            self.native_mut()
474                .readFromMemory(buffer.as_ptr() as _, buffer.len())
475        }
476    }
477
478    /// Transforms this rounded rectangle by `matrix` and returns it if possible. If the matrix does
479    /// not preserve axis-alignment (e.g. rotates, skews, etc.) then this returns `None`.
480    #[must_use]
481    pub fn transform(&self, matrix: &Matrix) -> Option<Self> {
482        let mut r = Self::default();
483        unsafe { self.native().transform1(matrix.native(), r.native_mut()) }.then_some(r)
484    }
485
486    /// Writes a text representation of this rounded rectangle to standard output. Set `as_hex` true
487    /// to generate exact binary representations of floating point numbers.
488    ///
489    /// - `as_hex` true if scalar values are written as hexadecimal
490    ///
491    /// Example (C++): <https://fiddle.skia.org/c/@RRect_dump>
492    pub fn dump(&self, as_hex: impl Into<Option<bool>>) {
493        unsafe { self.native().dump(as_hex.into().unwrap_or_default()) }
494    }
495
496    pub fn dump_to_string(&self, as_hex: bool) -> String {
497        let mut str = interop::String::default();
498        unsafe { sb::C_SkRRect_dumpToString(self.native(), as_hex, str.native_mut()) }
499        str.to_string()
500    }
501
502    pub fn dump_hex(&self) {
503        self.dump(true)
504    }
505}