Override or change opacity of a given RGBA color?

I’ve seen a construct like (:red, 0.3) to control the color and opacity separately. What I’d like to achieve here is to change the opacity of a given RGBA color. What’s the idiomatic way?

At the end of this message, I show a self-contained, simplified example (which currently uses a fake function that pretends to do what I want to do).

Probably, to people who are familiar with dealing with user-defined types (structs), this problem should be very simple. Currently, I don’t know how to (safely) copy a user-defined-type object. (Perhaps I should use copy()?) I also don’t know how to find out the names of the fields. (What’s the name of the alpha channel? Julia includes powerful reflection, so this should be easy.) I also don’t know whether direct assignment to a field is recommended/allowed or not. (In some languages, you use setter functions, instead of allowing for direct assignments.) In some languages, there are idioms like newobj = setfield(oldobj, fieldname = val) . . .

[In that sense, it may have been better to ask these questions in a different forum, but I just wondered whether there is an idiomatic color-specific way.]

using CairoMakie

Fake: ignores the input color and returns a fixed color.
function set_opacity(c, alpha)
return Makie.RGBA{Float32}(0.9019608f0,0.62352943f0,0.0f0,alpha)

xax = -π:(π/16):π
var1 = cos.(xax)
var2 = sin.(xax)
cs = Makie.wong_colors() # Vector of RGBAs
fig = Figure()
ax = Axis(fig[1,1])
lines!(ax, xax, var1; color=cs[2])
lines!(ax, xax, var2; color=set_opacity(cs[2], 0.3f0), linewidth=10)

In Makie you can also do (rgba_color, somealpha) although that will multiply. Otherwise there’s Colors.alphacolor I think

1 Like

Works! Thanks!

I see. That means that you need to know the alpha value of the original color. For my plots at hand, that is perfectly fine because all alpha values are 1 in wong_colors().

So, I guess what you do would be

newcol = copy(oldcol)
newcol.alphacolor = 0.3

I meant the alphacolor function from Colors.jl

1 Like

I see! I’ve just tried it. I think that’s the best way in that it doesn’t depend on Makie (and so it should work with other graphics packages, too):

julia> using Colors

julia> a = RGBA(0.5, 0.6, 0.7, 0.8)

julia> coloralpha(a, 0.1) # replace alpha
1 Like