generated from mistricky/nvim-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Feat] convert rgb hex color to rgba hex color
- Loading branch information
Showing
2 changed files
with
27 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,44 @@ | ||
use std::i64; | ||
use tiny_skia::Color; | ||
|
||
const HEX_COLOR_LENGTH: usize = 7; | ||
const HEX_COLOR_WITH_ALPHA_LENGTH: usize = 9; | ||
|
||
pub struct RgbaColor { | ||
pub color: Color, | ||
} | ||
|
||
pub fn is_valid_hex_color(color: &str) -> bool { | ||
(color.len() == HEX_COLOR_LENGTH || color.len() == HEX_COLOR_WITH_ALPHA_LENGTH) | ||
&& color.starts_with("#") | ||
} | ||
|
||
fn parse_color_to_rgba_hex(hex: &str) -> String { | ||
if !is_valid_hex_color(&hex) || hex.len() == HEX_COLOR_WITH_ALPHA_LENGTH { | ||
hex.to_string() | ||
} else { | ||
format!("{}ff", hex) | ||
} | ||
} | ||
|
||
impl Into<RgbaColor> for String { | ||
fn into(self) -> RgbaColor { | ||
let hex_color = &self.to_lowercase()[1..self.len()]; | ||
let rgba_hex_color = parse_color_to_rgba_hex(&self); | ||
// Remove the '#' symbol | ||
let hex_color = &rgba_hex_color.to_lowercase()[1..rgba_hex_color.len()]; | ||
let chars = hex_color.chars().collect::<Vec<char>>(); | ||
let splits = &chars | ||
.chunks(2) | ||
.map(|chunk| i64::from_str_radix(&chunk.iter().collect::<String>(), 16).unwrap()) | ||
.collect::<Vec<_>>(); | ||
|
||
let alpha: i64; | ||
match splits.get(3) { | ||
Some(x) => alpha = *x, | ||
None => alpha = 255, | ||
} | ||
|
||
RgbaColor { | ||
color: Color::from_rgba8(splits[0] as u8, splits[1] as u8, splits[2] as u8, alpha as u8), | ||
color: Color::from_rgba8( | ||
splits[0] as u8, | ||
splits[1] as u8, | ||
splits[2] as u8, | ||
splits[3] as u8, | ||
), | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters