LoginSignup
23
11

More than 3 years have passed since last update.

[Rust] 標準出力に色をつける - 3bit/8bit/24bit color

Posted at

本記事では標準出力で色つきの文字を使う方法を述べます.

本論

shell スクリプトなどでは ESC を表現するのに \e, \033, \x1b が利用できますが, Rust の文字列リテラルでは 16 進数表示である \x1b しか使えません. その点を除くと普通の ANSI カラーと同じです.

用途によっては適当なクレートの利用も考慮すべきかもしれません. 参考文献 1では termion (Windows では動作しない模様), ansi_term, termcolor が挙げられていましたが, どれも試してはいません.

コード例

3bit color

fn main() {
    {
        let color = 0;
        print!("\x1b[{}m\x1b[47mColor{}\x1b[m ", 30+color, color);
    }
    for color in 1..8 {
        print!("\x1b[{}mColor{}\x1b[m ", 30+color, color);
    }
    println!("");
}

2019-10-20 165248.jpg

Color0 (黒) のみ黒背景だと見えないので背景を白にしています.

8bit color (256-color)

fn main() {
    for color in 0..256 {
        print!("\x1b[38;5;{0}mColor{0:03}\x1b[m ", color);
        if color%8 == 7 {
            println!("");
        }
    }
}

2019-10-20 165214.jpg

24bit color (true color)

true color は 224 = 1.67e7 色を表示できるので, 全部表示するのは大変すぎます. なのでここではお手軽三色混合を試してみます. なお \u{2588} という文字です (en.wikipedia).

fn main() {
    for y in 0i32..32 {
        let mut line = String::new();

        for _ in 0..31-y {
            line.push_str(" ");
        }

        for x in -y..1+y {
            let r = 8 * ( x + y);
            let g = 8 * ( y - x );
            let b = 248 - 8*y;

            let s = format!("\x1b[38;2;{};{};{}m\u{2588}\x1b[m", r, g, b);
            line = line + &s;
        }

        println!("{}", line);
    }
}

2019-10-20 164814.jpg

参考文献

23
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
11