summaryrefslogtreecommitdiffstats
path: root/core/src/rotation.rs
blob: ebb85f3cf59090ed967ab1f237053f27727cbdf8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//! Control the rotation of some content (like an image) within a space.
use crate::{Radians, Size};

/// The strategy used to rotate the content.
///
/// This is used to control the behavior of the layout when the content is rotated
/// by a certain angle.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Rotation {
    /// The element will float while rotating. The layout will be kept exactly as it was
    /// before the rotation.
    ///
    /// This is especially useful when used for animations, as it will avoid the
    /// layout being shifted or resized when smoothly i.e. an icon.
    ///
    /// This is the default.
    Floating(Radians),
    /// The element will be solid while rotating. The layout will be adjusted to fit
    /// the rotated content.
    ///
    /// This allows you to rotate an image and have the layout adjust to fit the new
    /// size of the image.
    Solid(Radians),
}

impl Rotation {
    /// Returns the angle of the [`Rotation`] in [`Radians`].
    pub fn radians(self) -> Radians {
        match self {
            Rotation::Floating(radians) | Rotation::Solid(radians) => radians,
        }
    }

    /// Rotates the given [`Size`].
    pub fn apply(self, size: Size) -> Size {
        match self {
            Self::Floating(_) => size,
            Self::Solid(rotation) => {
                let radians = f32::from(rotation);

                Size {
                    width: (size.width * radians.cos()).abs()
                        + (size.height * radians.sin()).abs(),
                    height: (size.width * radians.sin()).abs()
                        + (size.height * radians.cos()).abs(),
                }
            }
        }
    }
}

impl Default for Rotation {
    fn default() -> Self {
        Self::Floating(Radians(0.0))
    }
}

impl From<Radians> for Rotation {
    fn from(radians: Radians) -> Self {
        Self::Floating(radians)
    }
}

impl From<f32> for Rotation {
    fn from(radians: f32) -> Self {
        Self::Floating(Radians(radians))
    }
}