Search code examples
colorsjulia

With Colors.jl, how to change `Color`'s alpha transparency value?


If I have a Colors.jl Color, such as HSLA(200,0.9,0.8,0.8), HSL(200,0.9,0.8,0.8), or RGB(200,100,100), is there a generic way to return a version of the color with a specified alpha transparency value (and promote the type if the input doesn't have an alpha value)?

E.g. something like set_alpha(in_color,alpha=0.9)


Solution

  • Use the function alphacolor() in the Colors package:

    julia> using Colors
    
    julia> c = RGBA(0.5, 0.5, 0.5, 1.0)
    RGBA{Float64}(0.5,0.5,0.5,1.0)
    
    julia> alphacolor(c, 0.3)
    ARGB{Float64}(0.5,0.5,0.5,0.3)
    
    julia> d = RGB(0.5, 0.5, 0.5)
    RGB{Float64}(0.5,0.5,0.5)
    
    julia> alphacolor(d, 0.3)
    ARGB{Float64}(0.5,0.5,0.5,0.3)
    

    This is the set_alpha function the OP wants. I learned this solution in

    https://discourse.julialang.org/t/override-or-change-opacity-of-a-given-rgba-color/106880