Skip to content

Commit

Permalink
fix: color from_hex support alpha channel
Browse files Browse the repository at this point in the history
  • Loading branch information
JiatLn committed May 18, 2023
1 parent dbb4939 commit 24857e1
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 5 deletions.
15 changes: 12 additions & 3 deletions src/color/from_space.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,22 @@ impl Color {
///
/// let color = Color::from_hex("#ff3399").unwrap();
/// assert_eq!(color.hex(), "#f39");
///
/// let color = Color::from_hex("#ff339933").unwrap();
/// assert_eq!(color.hex(), "#f393");
/// ```
pub fn from_hex(hex_str: &str) -> Result<Self> {
ColorSpace::valid_hex(hex_str)?;
let (r, g, b) = conversion::hex::hex2rgb(hex_str);
Ok(Color::new(r, g, b, 1.0))
let (r, g, b, a) = match hex_str.len() {
4 | 7 => {
let (r, g, b) = conversion::hex::hex2rgb(hex_str);
(r, g, b, 1.0)
}
5 | 9 => conversion::hex::hex2rgba(hex_str),
_ => anyhow::bail!("Got a error hex string!"),
};
Ok(Color::new(r, g, b, a))
}

/// Create a color from a color name.
///
/// Currently supported color names are:
Expand Down
24 changes: 22 additions & 2 deletions src/conversion/hex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ pub fn rgba2hex(color: (f64, f64, f64, f64)) -> String {

pub fn hex2rgb(hex: &str) -> (f64, f64, f64) {
let mut hex = String::from(hex);
let len = hex.len();
if len == 4 {
// #rgb -> #rrggbb
if hex.len() == 4 {
let mut hex_new = String::from("#");
for c in hex[1..].chars() {
hex_new.push(c);
Expand All @@ -39,6 +39,26 @@ pub fn hex2rgb(hex: &str) -> (f64, f64, f64) {
(r as f64, g as f64, b as f64)
}

pub fn hex2rgba(hex: &str) -> (f64, f64, f64, f64) {
let mut hex = String::from(hex);
// #rgba -> #rrggbbaa
if hex.len() == 5 {
let mut hex_new = String::from("#");
for c in hex[1..].chars() {
hex_new.push(c);
hex_new.push(c);
}
hex = hex_new;
}

let r = u8::from_str_radix(&hex[1..3], 16).unwrap();
let g = u8::from_str_radix(&hex[3..5], 16).unwrap();
let b = u8::from_str_radix(&hex[5..7], 16).unwrap();
let a = u8::from_str_radix(&hex[7..9], 16).unwrap();

(r as f64, g as f64, b as f64, (a as f64) / 255.0)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
3 changes: 3 additions & 0 deletions tests/color_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ fn test_color_marcos() {
let color = color!(#1890ff);
assert_eq!(color.hex(), "#1890ff");

let color = color!(#1890ff33);
assert_eq!(color.hex(), "#1890ff33");

let color = color!(rgb(255, 255, 0));
assert_eq!(color.rgb(), "rgb(255, 255, 0)");

Expand Down

0 comments on commit 24857e1

Please sign in to comment.