Skip to content

Commit

Permalink
fix: rgba to hex alpha value loss of accuracy
Browse files Browse the repository at this point in the history
  • Loading branch information
JiatLn committed Aug 30, 2023
1 parent ff01441 commit cc8bfc5
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 11 deletions.
1 change: 1 addition & 0 deletions src/color/stringify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ impl Color {
///
/// For example:
/// - `#ff00ff` -> `#f0f`
/// - `#ffffff88` -> `#fff8`
///
/// # Examples
///
Expand Down
17 changes: 7 additions & 10 deletions src/conversion/hex.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{utils::*, ALPHA_HEX_MAP};
use crate::utils::*;

pub fn rgb2hex(color: [f64; 3]) -> String {
let [r, g, b] = color;
Expand All @@ -10,14 +10,11 @@ pub fn rgb2hex(color: [f64; 3]) -> String {

pub fn rgba2hex(color: [f64; 4]) -> String {
let [r, g, b, a] = color;
let r = r.round() as u8;
let g = g.round() as u8;
let b = b.round() as u8;
let a = round(a, 2).to_string();
let a = ALPHA_HEX_MAP
.get(a.as_str())
.expect("alpha hex map error, please report this issue on github");
format!("#{:02x}{:02x}{:02x}{}", r, g, b, a)

let hex = rgb2hex([r, g, b]);
let alpha = round(a * 255.0, 0);

format!("{}{:02x}", hex, alpha as i64)
}

pub fn hex2rgb(hex: &str) -> Vec<f64> {
Expand Down Expand Up @@ -109,7 +106,7 @@ mod tests {

let rgba = [0.0, 128.0, 128.0, 0.222222];
let hex = rgba2hex(rgba);
assert_eq!(hex, "#00808038");
assert_eq!(hex, "#00808039");

let rgba = [0.0, 128.0, 128.0, 0.0];
let hex = rgba2hex(rgba);
Expand Down
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,5 @@ pub use color_calc::contrast_ratio::*;
pub use color_calc::delta_e::*;
pub use color_calc::distance::*;
pub use color_space::ColorSpace;
use data::alpha_hex_map::ALPHA_HEX_MAP;
use data::chinese_color::CHINESE_COLOR_HASHMAP as CHINESE_COLOR;
use data::w3cx11::W3CX11_HASHMAP as W3CX11;
12 changes: 12 additions & 0 deletions tests/color_hex.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use color_art::color;

#[test]
fn test_color_hex() {
let color = color!(#ffffff88);
assert_eq!(color.hex(), "#fff8");
assert_eq!(color.hex_full(), "#ffffff88");

let color = color!(#ff00ff);
assert_eq!(color.hex(), "#f0f");
assert_eq!(color.hex_full(), "#ff00ff");
}

0 comments on commit cc8bfc5

Please sign in to comment.