Hexadecimal colors and the Rust palette
Crate
My ongoing Rust tinkering found me wanting to fool around with color manipulation; I'd like to write a color exploration/palette generator web API and front end.
This led me to the palette crate, which I'm pretty sure does everything I need and then some, but because I'm still in "only know enough to be dangerous" mode with Rust, it took me a while to figure out how to instantiate an Rgb
struct directly from a web-style #abcdef
hexadecimal color string.
TL;DR, you can use the FromStr
trait:
Code:
use std::str::FromStr;
use palette::{rgb, Srgb};
let my_rgb: rgb::Rgb<Srgb, u8> = rgb::Rgb::from_str("336699").unwrap()
println!("{:?}", my_rgb);
Output:
Rgb { red: 51, green: 102, blue: 153, standard: PhantomData<palette::rgb::rgb::Rgb> }
rgb::Rgb::from_str()
supports strings with a leading octothorpe ("#336699"
), and it will also take a &String
instead of a literal.
Sat Nov 04 2023 20:00:00 GMT-0400 (Eastern Daylight Time)