Struct scarlet::color::RGBColor

source ·
pub struct RGBColor {
    pub r: f64,
    pub g: f64,
    pub b: f64,
}
Expand description

A color with red, green, and blue primaries of specified intensity, specifically in the sRGB gamut: most computer screens use this to display colors. The attributes r, g, and b are floating-point numbers from 0 to 1 for visible colors, allowing the avoidance of rounding errors or clamping errors when converting to and from RGB. Many conveniences are afforded so that working with RGB as if it were instead three integers from 0-255 is painless. Note that the integers generated from the underlying floating-point numbers round away from 0.

Examples of this abound: this is used ubiquitously in Scarlet. Check the Color documentation for plenty.

Fields§

§r: f64

The red component. Ranges from 0 to 1 for numbers displayable by sRGB machines.

§g: f64

The green component. Ranges from 0 to 1 for numbers displayable by sRGB machines.

§b: f64

The blue component. Ranges from 0 to 1 for numbers displayable by sRGB machines.

Implementations§

source§

impl RGBColor

source

pub fn int_r(&self) -> u8

Gets an 8-byte version of the red component, as a u8. Clamps values outside of the range 0-1 and discretizes, so this may not correspond to the exact values kept internally.

Example
let super_red = RGBColor{r: 1.2, g: 0., b: 0.};
let non_integral_red = RGBColor{r: 0.999, g: 0., b: 0.};
// the first one will get clamped in range, the second one will be rounded
assert_eq!(super_red.int_r(), non_integral_red.int_r());
assert_eq!(super_red.int_r(), 255);
source

pub fn int_g(&self) -> u8

Gets an 8-byte version of the green component, as a u8. Clamps values outside of the range 0-1 and discretizes, so this may not correspond to the exact values kept internally.

Example
let super_green = RGBColor{r: 0., g: 1.2, b: 0.};
let non_integral_green = RGBColor{r: 0., g: 0.999, b: 0.};
// the first one will get clamped in range, the second one will be rounded
assert_eq!(super_green.int_g(), non_integral_green.int_g());
assert_eq!(super_green.int_g(), 255);
source

pub fn int_b(&self) -> u8

Gets an 8-byte version of the blue component, as a u8. Clamps values outside of the range 0-1 and discretizes, so this may not correspond to the exact values kept internally.

Example
let super_blue = RGBColor{r: 0., g: 0., b: 1.2};
let non_integral_blue = RGBColor{r: 0., g: 0., b: 0.999};
// the first one will get clamped in range, the second one will be rounded
assert_eq!(super_blue.int_b(), non_integral_blue.int_b());
assert_eq!(super_blue.int_b(), 255);
source

pub fn int_rgb_tup(&self) -> (u8, u8, u8)

Purely for convenience: gives a tuple with the three integer versions of the components. Used over standard conversion traits to avoid ambiguous operations.

Example
let color = RGBColor{r: 0.3, g: 0.6, b: 0.7};
assert_eq!(color.int_rgb_tup(), (color.int_r(), color.int_g(), color.int_b()));
source§

impl RGBColor

source

pub fn from_hex_code(hex: &str) -> Result<RGBColor, RGBParseError>

Given a string that represents a hex code, returns the RGB color that the given hex code represents. Four formats are accepted: "#rgb" as a shorthand for "#rrggbb", #rrggbb by itself, and either of those formats without #: "rgb" or "rrggbb" are acceptable. Returns a ColorParseError if the given string does not follow one of these formats.

Example
let fuchsia = RGBColor::from_hex_code("#ff00ff")?;
// if 3 digits, interprets as doubled
let fuchsia2 = RGBColor::from_hex_code("f0f")?;
assert_eq!(fuchsia.int_rgb_tup(), fuchsia2.int_rgb_tup());
assert_eq!(fuchsia.int_rgb_tup(), (255, 0, 255));
let err = RGBColor::from_hex_code("#afafa");
let err2 = RGBColor::from_hex_code("#gafd22");
assert_eq!(err, err2);
source

pub fn from_color_name(name: &str) -> Result<RGBColor, RGBParseError>

Gets the RGB color corresponding to an X11 color name. Case is ignored.

Example
let fuchsia = RGBColor::from_color_name("fuchsia")?;
let fuchsia2 = RGBColor::from_color_name("FuCHSiA")?;
assert_eq!(fuchsia.int_rgb_tup(), fuchsia2.int_rgb_tup());
assert_eq!(fuchsia.int_rgb_tup(), (255, 0, 255));
let err = RGBColor::from_color_name("fuccshai");
let err2 = RGBColor::from_color_name("foobar");
assert_eq!(err, err2);
source§

impl RGBColor

source

pub fn from_material_palette(prim: MaterialPrimary) -> RGBColor

Gets a Color from the Material palette, given a specification of such a color.

Example
let red_400 = RGBColor::from_material_palette(MaterialPrimary::Red(MaterialTone::Neutral(NeutralTone::W400)));
let amber_a100 = RGBColor::from_material_palette(MaterialPrimary::Amber(MaterialTone::Accent(AccentTone::A100)));
assert_eq!(red_400.to_string(), "#EF5350");
assert_eq!(amber_a100.to_string(), "#FFE57F");

Trait Implementations§

source§

impl Bound for RGBColor

source§

fn bounds() -> [(f64, f64); 3]

Returns an array [(min1, max1), (min2, max2), (min3, max3)] that represents the bounds on each component of the color space, in the order that they appear in the Coord representation. If some parts of the bounds don’t exist, using infinity or negative infinity works.
source§

fn clamp_coord(point: Coord) -> Coord

Given a Coord, returns a Coord such that each component has been clamped to the correct bounds. See trait documentation for example usage.
source§

fn clamp<T: ColorPoint>(color: T) -> T

Given a Color that can be embedded in 3D space, returns a new version of that color that is in the bounds of this color space, even if the coordinate systems of the two spaces differ. If the color is already in the gamut, it simply returns a copy. See trait documentation for example usage.
source§

impl Clone for RGBColor

source§

fn clone(&self) -> RGBColor

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 Color for RGBColor

source§

fn from_xyz(xyz: XYZColor) -> RGBColor

Converts from a color in CIE 1931 XYZ to the given color type. Read more
source§

fn to_xyz(&self, illuminant: Illuminant) -> XYZColor

Converts from the given color type to a color in CIE 1931 XYZ space. Because most color types don’t include illuminant information, it is provided instead, as an enum. For most applications, D50 or D65 is a good choice. Read more
source§

fn convert<T: Color>(&self) -> T

Converts generic colors from one representation to another. This is done by going back and forth from the CIE 1931 XYZ space, using the illuminant D50 (although this should not affect the results). Just like collect() and other methods in the standard library, the use of type inference will usually allow for clean syntax, but occasionally the turbofish is necessary. Read more
source§

fn hue(&self) -> f64

Gets the generally most accurate version of hue for a given color: the hue coordinate in CIELCH. There are generally considered four “unique hues” that humans perceive as not decomposable into other hues (when mixing additively): these are red, yellow, green, and blue. These unique hues have values of 0, 90, 180, and 270 degrees respectively, with other colors interpolated between them. This returned value will never be outside the range 0 to 360. For more information, you can start at the Wikpedia page. Read more
source§

fn set_hue(&mut self, new_hue: f64)

Sets a perceptually-accurate version hue of a color, even if the space itself does not have a conception of hue. This uses the CIELCH version of hue. To use another one, simply convert and set it manually. If the given hue is not between 0 and 360, it is shifted in that range by adding multiples of 360. Read more
source§

fn lightness(&self) -> f64

Gets a perceptually-accurate version of lightness as a value from 0 to 100, where 0 is black and 100 is pure white. The exact value used is CIELAB’s definition of luminance, which is generally considered a very good standard. Note that this is nonlinear with respect to the physical amount of light emitted: a material with 18% reflectance has a lightness value of 50, not 18. Read more
source§

fn set_lightness(&mut self, new_lightness: f64)

Sets a perceptually-accurate version of lightness, which ranges between 0 and 100 for visible colors. Any values outside of this range will be clamped within it. Read more
source§

fn chroma(&self) -> f64

Gets a perceptually-accurate version of chroma, defined as colorfulness relative to a similarly illuminated white. This has no explicit upper bound, but is always positive and generally between 0 and 180 for visible colors. This is done using the CIELCH model. Read more
source§

fn set_chroma(&mut self, new_chroma: f64)

Sets a perceptually-accurate version of chroma, defined as colorfulness relative to a similarly illuminated white. Uses CIELCH’s defintion of chroma for implementation. Any value below 0 will be clamped up to 0, but because the upper bound depends on the hue and lightness no clamping will be done. This means that this method has a higher chance than normal of producing imaginary colors and any output from this method should be checked. Read more
source§

fn saturation(&self) -> f64

Gets a perceptually-accurate version of saturation, defined as chroma relative to lightness. Generally ranges from 0 to around 10, although exact bounds are tricky. from This means that e.g., a very dark purple could be very highly saturated even if it does not seem so relative to lighter colors. This is computed using the CIELCH model and computing chroma divided by lightness: if the lightness is 0, the saturation is also said to be 0. There is no official formula except ones that require more information than this model of colors has, but the CIELCH formula is fairly standard. Read more
source§

fn set_saturation(&mut self, new_sat: f64)

Sets a perceptually-accurate version of saturation, defined as chroma relative to lightness. Does this without modifying lightness or hue. Any negative value will be clamped to 0, but because the maximum saturation is not well-defined any positive value will be used as is: this means that this method is more likely than others to produce imaginary colors. Uses the CIELCH color space. Generally, saturation ranges from 0 to about 1, but it can go higher. Read more
source§

fn grayscale(&self) -> Selfwhere Self: Sized,

Returns a new Color of the same type as before, but with chromaticity removed: effectively, a color created solely using a mix of black and white that has the same lightness as before. This uses the CIELAB luminance definition, which is considered a good standard and is perceptually accurate for the most part. Read more
source§

fn distance<T: Color>(&self, other: &T) -> f64

Returns a metric of the distance between the given color and another that attempts to accurately reflect human perception. This is done by using the CIEDE2000 difference formula, the current international and industry standard. The result, being a distance, will never be negative: it has no defined upper bound, although anything larger than 100 would be very extreme. A distance of 1.0 is conservatively the smallest possible noticeable difference: anything that is below 1.0 is almost guaranteed to be indistinguishable to most people. Read more
source§

fn visually_indistinguishable<T: Color>(&self, other: &T) -> bool

Using the metric that two colors with a CIEDE2000 distance of less than 1 are indistinguishable, determines whether two colors are visually distinguishable from each other. For more, check out this guide. Read more
source§

impl Debug for RGBColor

source§

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

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

impl From<(u8, u8, u8)> for RGBColor

source§

fn from(rgb: (u8, u8, u8)) -> RGBColor

Converts to this type from the input type.
source§

impl From<Coord> for RGBColor

source§

fn from(c: Coord) -> RGBColor

Converts to this type from the input type.
source§

impl From<RGBColor> for (u8, u8, u8)

source§

fn from(val: RGBColor) -> Self

Converts to this type from the input type.
source§

impl From<RGBColor> for Coord

source§

fn from(val: RGBColor) -> Self

Converts to this type from the input type.
source§

impl FromStr for RGBColor

§

type Err = RGBParseError

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<RGBColor, RGBParseError>

Parses a string s to return a value of this type. Read more
source§

impl PartialEq<RGBColor> for RGBColor

source§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl ToString for RGBColor

source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl Copy for RGBColor

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> ColorPoint for Twhere T: Color + Into<Coord> + From<Coord> + Copy + Clone,

source§

fn euclidean_distance(self, other: Self) -> f64

Gets the Euclidean distance between these two points when embedded in 3D space. This should not be used as an analog of color similarity: use the distance() function for that.
source§

fn weighted_midpoint(self, other: Self, weight: f64) -> Self

Gets the weighted midpoint of two colors in a space as a new Color. This is defined as the color corresponding to the point along the line segment connecting the two points such that the distance to the second point is the weight, which for most applications needs to be between 0 and 1. For example, a weight of 0.9 would make the midpoint one-tenth as much affected by the second points as the first.
source§

fn midpoint(self, other: Self) -> Self

Like weighted_midpoint, but with weight = 0.5: essentially, the Color representing the midpoint of the two inputs in 3D space.
source§

fn weighted_average( self, others: Vec<Self>, weights: Vec<f64> ) -> Result<Self, ColorCalcError>

Returns the weighted average of a given set of colors. Weights will be normalized so that they sum to 1. Each component of the final value will be calculated by summing the components of each of the input colors multiplied by their given weight. Read more
source§

fn average(self, others: Vec<Self>) -> Coord

Returns the arithmetic mean of a given set of colors. Equivalent to weighted_average in the case where each weight is the same.
source§

fn is_imaginary(&self) -> bool

Returns true if the color is outside the range of human vision. Uses the CIE 1931 standard observer spectral data.
source§

fn closest_real_color(&self) -> Self

Returns the closest color that can be seen by the human eye. If the color is not imaginary, returns itself.
source§

fn gradient_scale(&self, other: &Self, n: usize) -> Vec<Self>

Returns a Vector of colors that starts with this color, ends with the given other color, and evenly transitions between colors. The given n is the number of additional colors to add.
source§

fn gradient(&self, other: &Self) -> Box<dyn Fn(f64) -> Self>

Returns a pointer to a function that maps floating-point values from 0 to 1 to colors, such that 0 returns self, 1 returns other, and anything in between returns a mix (calculated linearly). Although it is possible to extrapolate outside of the range [0, 1], this is not a guarantee and may change without warning. For more fine-grained control of gradients, see the GradientColorMap struct. Read more
source§

fn cbrt_gradient(&self, other: &Self) -> Box<dyn Fn(f64) -> Self>

Returns a pointer to a function that maps floating-point values from 0 to 1 to colors, such that 0 returns self, 1 returns other, and anything in between returns a mix (calculated by the cube root of the given value). Although it is possible to extrapolate outside of the range [0, 1], this is not a guarantee and may change without warning. For more fine-grained control of gradients, see the GradientColorMap struct. Read more
source§

fn padded_gradient( &self, other: &Self, lower_pad: f64, upper_pad: f64 ) -> Box<dyn Fn(f64) -> Self>

Returns a pointer to a function that maps floating-point values from 0 to 1 to colors with padding lower_pad and upper_pad such that an input of 0 returns the gradient at lower_pad, an input of 1 returns the gradient at upper_pad, and values in-between are mapped linearly inside that range. For more fine-grained control over gradients, see the GradientColorMap struct. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere 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> Same<T> for T

§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SPwhere SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
source§

impl<T> ToOwned for Twhere T: Clone,

§

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 Twhere U: Into<T>,

§

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 Twhere U: TryFrom<T>,

§

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.
source§

impl<G1, G2> Within<G2> for G1where G2: Contains<G1>,

source§

fn is_within(&self, b: &G2) -> bool

source§

impl<T> Scalar for Twhere T: 'static + Clone + PartialEq<T> + Debug,