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

Viewed 39

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)

2 Answers

You can use the color in its non-alpha version in a constructor for the one with an alpha:

julia> a = HSL(200.0, 0.8, 0.8)
HSL{Float64}(200.0,0.8,0.8)

julia> aa = HSLA(a, 0.5)
HSLA{Float64}(200.0,0.8,0.8,0.5)

Colors are defined as immutable structs for efficiency. Thus changing a field requires creating a new immutable. Turns out someone (Jan Weidner) wrote a package to do just that, Accessors.jl. So with this package it is possible to write:


julia> using Colors, Accessors

julia> c = HSLA(100,0.1,0.1,0.8)
HSLA{Float64}(100.0,0.1,0.1,0.8)

julia> @set c.alpha = 0.3
HSLA{Float64}(100.0,0.1,0.1,0.3)

Looks quite simple. Perhaps a package which defines more readable functions for these manipulations would be nice, but my googling attempts haven't found it.

Another option, inspired by @Bill's answer is

HSLA(HSL(c),0.2)

which does the same (inner HSL projects and HSLA adds back a transaparancy value)

Related