How to print text with a specified RGB value in Julia?
Asked Answered
S

3

8

For example, say I want to print text using the following color:

R: 0.5

G: 0.8

B: 0.1

I know about print_with_color() but as far as I know it has to use a Symbol to print, and I do not know how to create one for any arbitrary color, or if that is actually possible.

Sthilaire answered 13/1, 2015 at 19:12 Comment(1)
Its not possible to do this in a cross-platform friendly way, so its not provided in base Julia.Pinna
C
4

Possibly:

julia> function print_rgb(r, g, b, t)
           print("\e[1m\e[38;2;$r;$g;$b;249m",t)
       end
print_rgb (generic function with 1 method)

julia> for i in 0:100
           print_rgb(rand(0:255), rand(0:255), rand(0:255), "hello!")
       end

Julia terminal with pretty colors

Candracandy answered 13/1, 2015 at 19:51 Comment(2)
It works sometimes, but for most colors it just prints either gray text or a gray box. Any ideas why it might work like this?Sthilaire
The precise behavior of this depends on your terminal emulator. If your terminal emulator supports RGB colors, this should work.Allpowerful
C
3

You might try Crayons.jl. Your specification is float, and Crayons expects specification of 0-255, so some conversion is necessary:

julia> import Pkg; Pkg.add("Crayons")
julia> using Crayons
julia> a = (0.5, 0.8, 0.1)
(0.5, 0.8, 0.1)

julia> b = round.(Int, a .* 255)
(128, 204, 26)

julia> print(Crayon(foreground = b) , "My color string.")

Crayons.jl also supports hex RGB specification in string macros:

julia> print(crayon"#80cc1a", "My color string.")
Clance answered 3/9, 2020 at 17:25 Comment(0)
U
3

You might try 'printstyled' from 'Base' package, it require at least julia 1.7.

printstyled("pouet pouet"; color = :blue, blink = true)
Urumchi answered 12/10, 2022 at 14:13 Comment(1)
Nice to use a baked-in solution, but OP asked for RGB values. I hope I'm wrong, but printstyled() doesn't seem to support those.Tena

© 2022 - 2024 — McMap. All rights reserved.