Rust颜色处理库colorz的使用,高效实现RGB/HEX/HSL色彩转换与调色板生成
Rust颜色处理库colorz的使用,高效实现RGB/HEX/HSL色彩转换与调色板生成
colorz是一个零分配、兼容no_std
的终端输出着色库!它是owo-colors的一个"分支",但提供了更多功能。
use colorz::{Colorize, xterm};
// 将以红色打印"hello world"
println!("{}", "hello world".red());
// 将以红色背景打印"hello world"
println!("{}", "hello world".on_red());
// 将以Aqua下划线打印"hello world"
println!("{}", "hello world".underline_color(xterm::Aqua).underline());
特性
- 使用任何
std
格式化特性进行格式化(Display
、Debug
等) - 使用自定义格式函数格式化(
StyledValue::fmt_with
) - 通过
StyledValue::stream
实现每个值的条件样式 - 通过以下方式实现所有
StyledValue
的全局条件样式:colorz::mode
strip-colors
特性标志
- 默认零依赖
- 为Ansi、Xterm和Css颜色提供标准名称
- 支持RGB颜色
- Ansi修饰符(粗体、斜体、下划线等)
- 多颜色支持(前景色、背景色和下划线颜色)
- 对于简单情况,基本上是
owo-colors
的替代品- (某些xterm颜色名称可能不同,某些方法的调用方式略有不同)
- 通过颜色代码在编译时选择xterm颜色
- 编译时样式构建
- 编译时样式值构建
NO_COLOR
/ALWAYS_COLOR
环境变量:colorz::mode::{Mode::from_env, set_coloring_mode_from_env}
- 需要
std
或supports-color
特性
- 需要
特性标志
这个crate有几个特性标志:
strip-colors
- 移除所有StyledValue
格式化方法的着色std
- 启用标准库(因为这个库默认是no_std
)supports-color
- 启用supports-color
crate(它也使用std
库)
默认情况下没有启用任何特性。它们应该只由最终的二进制crate启用。
如果这些特性被关闭,则只尊重全局模式设置,并且不进行基于流的颜色检测。
如果启用了strip-colors
,则colorz::mode::get_coloring_mode
将总是返回Mode::Never
,并且StyledValue
永远不会被着色。
否则,如果启用了supports-color
,则使用supports-color
crate来检测是否支持ANSI、Xterm或RGB颜色。如果一个StyledValue
尝试使用任何不支持的颜色类型,则它不会进行任何着色。例如,如果你的终端不支持Xterm颜色,而你写了
use colorz::{Colorize, xterm};
println!("{}", "hello world".fg(xterm::Red));
那么你将看到终端默认颜色的hello world
。
最后,如果启用了std
,那么如果流是一个终端,则使用所有颜色类型;如果流不是一个终端,则不选择任何颜色。
完整示例代码
use colorz::{Colorize, Style, xterm, css, mode::Stream, Effect};
fn main() {
// 基本颜色使用
println!("{}", "这是红色文本".red());
println!("{}", "这是绿色背景文本".on_green());
// RGB颜色转换
println!("RGB红色: {}", "RGB(255,0,0)".fg_rgb(255, 0, 0));
// HEX颜色转换
println!("HEX绿色: {}", "#00FF00".fg(css::Green));
// HSL颜色表示(通过RGB实现)
let hsl_blue = Style::new().fg_rgb(0, 0, 255);
println!("HSL蓝色: {}", "Hue:240°, Saturation:100%, Lightness:50%".style_with(hsl_blue));
// 调色板生成与展示
let palette = [
xterm::Red,
xterm::Green,
xterm::Blue,
xterm::Yellow,
xterm::Magenta,
xterm::Cyan,
xterm::Orange,
xterm::Purple
];
println!("\n调色板展示:");
for (i, color) in palette.iter().enumerate() {
println!("颜色{}: {}", i, "■■■■■■".fg(*color));
}
// 条件着色
let is_error = true;
let message = "这是一个条件着色的消息";
println!("\n条件着色示例:");
println!("{}", message.fg(if is_error { xterm::Red } else { xterm::Green }));
// 全局模式设置
colorz::mode::set_coloring_mode(colorz::mode::Mode::Always);
// 编译时样式定义
const ERROR_STYLE: Style = Style::new()
.fg(xterm::Red)
.effects_array([Effect::Bold, Effect::Underline])
.const_into_runtime_style();
const SUCCESS_STYLE: Style = Style::new()
.fg(xterm::Green)
.effects_array([Effect::Bold])
.const_into_runtime_style();
println!("\n编译时样式示例:");
println!("{}", "错误信息".style_with(ERROR_STYLE));
println!("{}", "成功信息".style_with(SUCCESS_STYLE));
// 组合样式示例
println!("\n组合样式示例:");
println!("{}", "红色粗体带下划线"
.fg(xterm::Red)
.bold()
.underline());
}
安装
在项目目录中运行以下Cargo命令:
cargo add colorz
或者在Cargo.toml中添加以下行:
colorz = "1.1.4"
许可证
MIT OR Apache-2.0
Rust颜色处理库colorz使用指南
colorz是一个高效的Rust颜色处理库,提供了RGB、HEX、HSL等色彩模型的转换功能以及调色板生成能力。
主要特性
- RGB、HEX、HSL颜色格式相互转换
- 调色板生成功能
- 颜色混合与调整
- 高性能实现
安装
在Cargo.toml中添加依赖:
[dependencies]
colorz = "0.3"
基本使用
颜色创建与转换
use colorz::{Color, Rgb, Hsl, Hex};
fn main() {
// 从RGB创建颜色
let red = Rgb::new(255, 0, 0);
// 转换为HSL
let red_hsl: Hsl = red.into();
println!("Red in HSL: {:?}", red_hsl);
// 从HEX字符串创建
let blue = Hex::from_str("#0000FF").unwrap();
println!("Blue from HEX: {:?}", blue);
// 转换为RGB
let blue_rgb: Rgb = blue.into();
println!("Blue in RGB: {:?}", blue_rgb);
}
颜色调整
use colorz::{Rgb, Hsl};
fn main() {
let mut green = Rgb::new(0, 128, 0);
// 调亮颜色
green.lighten(10);
println!("Lighter green: {:?}", green);
// 转换为HSL并调整饱和度
let mut green_hsl: Hsl = green.into();
green_hsl.saturate(20);
println!("More saturated green: {:?}", green_hsl);
}
调色板生成
use colorz::{Rgb, Palette};
fn main() {
let base_color = Rgb::new(100, 150, 200);
// 生成单色调色板
let monochromatic = Palette::monochromatic(&base_color, 5);
println!("Monochromatic palette: {:?}", monochromatic);
// 生成互补色调色板
let complementary = Palette::complementary(&base_color, 3);
println!("Complementary palette: {:?}", complementary);
// 生成类似色调色板
let analogous = Palette::analogous(&base_color, 5, 30.0);
println!("Analogous palette: {:?}", analogous);
}
高级功能
颜色混合
use colorz::{Rgb, BlendMode};
fn main() {
let red = Rgb::new(255, 0, 0);
let blue = Rgb::new(0, 0, 255);
// 混合颜色
let purple = red.blend(&blue, BlendMode::Multiply);
println!("Red multiplied by blue: {:?}", purple);
// 线性插值混合
let gradient = red.mix(&blue, 0.5);
println!("50% mix of red and blue: {:?}", gradient);
}
颜色对比度计算
use colorz::{Rgb, contrast_ratio};
fn main() {
let black = Rgb::new(0, 0, 0);
let white = Rgb::new(255, 255, 255);
let ratio = contrast_ratio(&black, &white);
println!("Contrast ratio between black and white: {:.2}", ratio);
// WCAG 2.1建议最小对比度为4.5:1
if ratio >= 4.5 {
println!("This contrast meets WCAG 2.1 AA standard");
}
}
性能提示
colorz在设计上注重性能:
- 使用整数运算而非浮点数运算
- 尽量减少内存分配
- 提供无panic的API
对于批量处理颜色,建议使用迭代器模式:
use colorz::{Rgb, Palette};
fn process_colors(colors: &[Rgb]) -> Vec<Rgb] {
colors.iter()
.map(|c| c.darken(10))
.collect()
}
colorz库适合需要高性能颜色处理的Rust应用,如图形处理、数据可视化、游戏开发等场景。
完整示例demo
下面是一个综合使用colorz库的完整示例,展示了多种颜色操作:
use colorz::{Color, Rgb, Hsl, Hex, Palette, BlendMode, contrast_ratio};
fn main() {
// 1. 颜色创建与转换
println!("=== 颜色创建与转换 ===");
let red = Rgb::new(255, 0, 0);
let red_hsl: Hsl = red.into();
println!("红色 (RGB): {:?}", red);
println!("红色 (HSL): {:?}", red_hsl);
let cyan = Hex::from_str("#00FFFF").unwrap();
let cyan_rgb: Rgb = cyan.into();
println!("青色 (HEX): {:?}", cyan);
println!("青色 (RGB): {:?}", cyan_rgb);
// 2. 颜色调整
println!("\n=== 颜色调整 ===");
let mut purple = Rgb::new(128, 0, 128);
println!("原始紫色: {:?}", purple);
purple.lighten(15);
println!("调亮15%后: {:?}", purple);
let mut purple_hsl: Hsl = purple.into();
purple_hsl.desaturate(30);
println!("降低饱和度30%后: {:?}", purple_hsl);
// 3. 调色板生成
println!("\n=== 调色板生成 ===");
let primary = Rgb::new(255, 165, 0); // 橙色
let shades = Palette::monochromatic(&primary, 5);
println!("单色调色板 (5种): {:?}", shades);
let triadic = Palette::complementary(&primary, 3);
println!("互补色调色板 (3种): {:?}", triadic);
// 4. 颜色混合
println!("\n=== 颜色混合 ===");
let yellow = Rgb::new(255, 255, 0);
let blue = Rgb::new(0, 0, 255);
let multiply = yellow.blend(&blue, BlendMode::Multiply);
println!("黄色与蓝色相乘混合: {:?}", multiply);
let overlay = yellow.blend(&blue, BlendMode::Overlay);
println!("黄色与蓝色叠加混合: {:?}", overlay);
let gradient = yellow.mix(&blue, 0.3);
println!("30%黄色与70%蓝色混合: {:?}", gradient);
// 5. 颜色对比度
println!("\n=== 颜色对比度 ===");
let dark_gray = Rgb::new(50, 50, 50);
let light_gray = Rgb::new(200, 200, 200);
let ratio = contrast_ratio(&dark_gray, &light_gray);
println!("对比度比率: {:.2}", ratio);
if ratio >= 4.5 {
println!("符合WCAG 2.1 AA标准");
} else {
println!("不符合WCAG 2.1 AA标准");
}
// 6. 批量处理颜色
println!("\n=== 批量处理颜色 ===");
let colors = vec![
Rgb::new(255, 0, 0),
Rgb::new(0, 255, 0),
Rgb::new(0, 0, 255)
];
let darkened: Vec<Rgb> = colors.iter()
.map(|c| {
let mut color = *c;
color.darken(20);
color
})
.collect();
println!("原始颜色: {:?}", colors);
println!("调暗20%后: {:?}", darkened);
}
这个完整示例演示了:
- 颜色创建与不同格式间的转换
- 颜色亮度、饱和度的调整
- 多种调色板生成方式
- 不同混合模式的颜色混合
- 颜色对比度计算和WCAG标准检查
- 使用迭代器批量处理颜色
运行此示例将输出各种颜色操作的结果,帮助您全面了解colorz库的功能。