Struct Color

Source
pub struct Color { /* private fields */ }
Expand description

A color in RGBA form, optionally with an alpha channel.

Internally, stores:

  • r, g, b as 8-bit values.
  • a as an f32 in [0..1].
  • a boolean has_alpha indicating whether the color has transparency.

This struct offers methods to create and manipulate colors in a CSS/Sass-like manner (e.g. grayscale(), invert(), mix(), etc.).

Implementations§

Source§

impl Color

Source

pub fn new(r: u8, g: u8, b: u8, a: f32) -> Self

Creates a new color from RGBA components.

§Arguments
  • r - Red channel (0..255).
  • g - Green channel (0..255).
  • b - Blue channel (0..255).
  • a - Alpha channel (0..1). If a < 1.0, color is considered to have alpha.
§Examples
use grimoire_css_lib::color::Color;

let c = Color::new(255, 0, 0, 1.0); // Fully opaque red
Source

pub fn from_rgb(r: u8, g: u8, b: u8, a: f32) -> Self

Creates a color from RGB and alpha components.

Equivalent to Color::new, provided for clarity.

Source

pub fn from_hsl(h: f32, s: f32, l: f32, a: f32) -> Self

Creates a color from HSL values, plus alpha.

§Arguments
  • h - Hue, in degrees (0..360).
  • s - Saturation, in percent (0..100).
  • l - Lightness, in percent (0..100).
  • a - Alpha channel (0..1).
§Examples
use grimoire_css_lib::color::Color;

// Pure red via HSL
let c = Color::from_hsl(0.0, 100.0, 50.0, 1.0);
Source

pub fn from_hwb(h: f32, w: f32, bk: f32, a: f32) -> Self

Creates a color from HWB values, plus alpha.

§Arguments
  • h - Hue in degrees (0..360).
  • w - Whiteness (0..100).
  • bk - Blackness (0..100).
  • a - Alpha channel (0..1).

See the CSS spec.

Source

pub fn from_hex(hex: &str) -> Option<Self>

Attempts to create a color from a hex string (e.g. "#ff00ff", "#fff"). Returns None if the string is invalid.

Supports 3-, 4-, 6-, and 8-digit hex forms (including alpha).

Source

pub fn try_from_str(input: &str) -> Option<Self>

Attempts to create a color from a general CSS-like string:

  • Named color (e.g. "red", "aliceblue")
  • Hex code (e.g. "#fff", "#ff00ff", "#ffffffff")
  • Functional notation (e.g. "rgb(...)", "hsl(...)", "hwb(...)")

Returns None if the color cannot be parsed.

Source

pub fn red(&self) -> u8

Returns the red channel (0..255)

Source

pub fn green(&self) -> u8

Returns the green channel (0..255)

Source

pub fn blue(&self) -> u8

Returns the blue channel (0..255)

Source

pub fn alpha(&self) -> f32

Returns the alpha channel (0..1)

Source

pub fn opacity(&self) -> f32

Alias for alpha()

Source

pub fn to_hsl(&self) -> (f32, f32, f32)

Converts the current color to HSL and returns (h, s, l) where:

  • h is in [0..360] degrees,
  • s and l are in [0..100] percent.

This does not change the alpha channel.

§Examples
use grimoire_css_lib::color::Color;

let c = Color::new(255, 0, 0, 1.0);
let (h, s, l) = c.to_hsl();
assert_eq!(h, 0.0);
assert_eq!(s, 100.0);
assert_eq!(l, 50.0);
Source

pub fn to_rgba(&self) -> (u8, u8, u8, f32)

Returns (r,g,b,a) with:

  • r,g,b in [0..255]
  • a in [0..1]
Source

pub fn to_hex_string(&self) -> String

Returns a CSS hex string (e.g. "#7fffd4" or "#7fffd480" if alpha < 1.0).

§Examples
use grimoire_css_lib::color::Color;

let c = Color::new(127, 255, 212, 1.0);
assert_eq!(c.to_hex_string(), "#7fffd4");
Source

pub fn to_named_color_str(&self) -> Option<&'static str>

Returns the named color string (e.g. "red", "blue") if this color matches one of the predefined colors exactly, otherwise None.

§Examples
use grimoire_css_lib::color::Color;

let c = Color::new(255, 0, 0, 1.0);
assert_eq!(c.to_named_color_str(), Some("red"));
Source

pub fn grayscale(&self) -> Self

Converts the color to grayscale by setting saturation to 0%.

Other channels (hue, lightness, alpha) remain unchanged.

Source

pub fn complement(&self) -> Self

Returns the complementary color by adding 180° to the hue.

Source

pub fn invert(&self, weight: Option<f32>) -> Self

Inverts the color.

weight controls how much the color is inverted (0..100%, defaults to 100).

§Examples
use grimoire_css_lib::color::Color;

let white = Color::new(255, 255, 255, 1.0);
let black = white.invert(None);
assert_eq!(black.to_hex_string(), "#000000");
Source

pub fn mix(c1: Color, c2: Color, weight: f32) -> Self

Mixes two colors by a given weight (0..100%).

A weight of 50% returns an average of the two colors.

§Examples
use grimoire_css_lib::color::Color;

let red = Color::new(255, 0, 0, 1.0);
let blue = Color::new(0, 0, 255, 1.0);
let purple = Color::mix(red, blue, 50.0);
assert_eq!(purple.to_hex_string(), "#800080");
Source

pub fn adjust_hue(&self, degrees: f32) -> Self

Adjusts the hue by degrees.

If degrees is positive, hue rotates “forward”; if negative, it rotates “backward”. Values can wrap beyond 360°.

Source

pub fn adjust_color( &self, red_delta: Option<i32>, green_delta: Option<i32>, blue_delta: Option<i32>, hue_delta: Option<f32>, sat_delta: Option<f32>, light_delta: Option<f32>, alpha_delta: Option<f32>, ) -> Self

Adjusts color by optionally modifying RGB deltas or HSL deltas.

§Arguments
  • red_delta, green_delta, blue_delta - The integer deltas to add to each channel.
  • hue_delta, sat_delta, light_delta, alpha_delta - The float deltas for hue, saturation, lightness, alpha.

Missing arguments (i.e. None) leave that component unchanged.

§Examples
use grimoire_css_lib::color::Color;

let c = Color::new(128, 128, 128, 1.0);
// Make it slightly redder
let c2 = c.adjust_color(Some(10), None, None, None, None, None, None);
Source

pub fn change_color( &self, red: Option<u8>, green: Option<u8>, blue: Option<u8>, hue_val: Option<f32>, sat_val: Option<f32>, light_val: Option<f32>, alpha_val: Option<f32>, ) -> Self

Changes color by setting absolute values (if provided) for RGB or HSL.

§Arguments
  • red, green, blue - Final values for each channel (0..255).
  • hue_val, sat_val, light_val - Final HSL values.
  • alpha_val - Final alpha in [0..1].

Missing arguments (i.e. None) leave that component unchanged.

Source

pub fn scale_color( &self, red_scale: Option<f32>, green_scale: Option<f32>, blue_scale: Option<f32>, saturation_scale: Option<f32>, lightness_scale: Option<f32>, alpha_scale: Option<f32>, ) -> Self

Scales color channels by given percentages.

Positive scale values increase the channel, negative decrease. E.g. red_scale=10.0 => +10% red from current value.

Missing arguments (i.e. None) leave that channel unchanged.

Source

pub fn rgba(&self, alpha: f32) -> Self

Returns a new color with the same RGB, but alpha set to alpha.

§Examples
use grimoire_css_lib::color::Color;

let c = Color::new(255, 0, 0, 1.0);
let half_transparent_red = c.rgba(0.5);
Source

pub fn lighten(&self, amount: f32) -> Self

Lightens the color by amount percent.

§Examples
use grimoire_css_lib::color::Color;

let red = Color::new(255, 0, 0, 1.0);
let lighter_red = red.lighten(10.0); // ~ #ff3333
Source

pub fn darken(&self, amount: f32) -> Self

Darkens the color by amount percent.

Source

pub fn saturate(&self, amount: f32) -> Self

Increases saturation by amount percent

Source

pub fn desaturate(&self, amount: f32) -> Self

Decreases saturation by amount percent

Source

pub fn opacify(&self, amount: f32) -> Self

Increases alpha by amount in [0..1], making the color more opaque.

§Examples
use grimoire_css_lib::color::Color;

let mut c = Color::new(255, 0, 0, 0.5);
c = c.opacify(0.3);  // new alpha = 0.8
Source

pub fn fade_in(&self, amount: f32) -> Self

Alias for opacify

Source

pub fn transparentize(&self, amount: f32) -> Self

Decreases alpha (increases transparency) by amount (0..1)

Source

pub fn fade_out(&self, amount: f32) -> Self

Alias for transparentize

Trait Implementations§

Source§

impl Clone for Color

Source§

fn clone(&self) -> Color

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Color

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Hash for Color

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Color

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Copy for Color

Source§

impl Eq for Color

Auto Trait Implementations§

§

impl Freeze for Color

§

impl RefUnwindSafe for Color

§

impl Send for Color

§

impl Sync for Color

§

impl Unpin for Color

§

impl UnwindSafe for Color

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CallHasher for T
where T: Hash + ?Sized,

Source§

default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64
where H: Hash + ?Sized, B: BuildHasher,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<F, W, T, D> Deserialize<With<T, W>, D> for F
where W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized,

Source§

fn deserialize( &self, deserializer: &mut D, ) -> Result<With<T, W>, <D as Fallible>::Error>

Deserializes using the given deserializer
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The type for metadata in pointers and references to Self.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.