Compensate for Transparency

Kristjan Kannike, created 2022-07-19, changed 2022-07-21

Compensate for transparency by making a colour darker, so it will look the same:

compensateTransparency[col_?ColorQ,as_?NumericQ]:=With[{colspace=Head[col],rgbcol=ColorConvert[col,RGBColor]},
If[(Min@@rgbcol)<1-as,Print[StringForm["Warning: the original color is too dark to be compensated for opacity ``",as]]];
ColorConvert[(-1+as+#)/as&/@rgbcol,
colspace]];

lightred=;
lightblue=;

Partially overlapping squares with opaque colours:

Graphics[{lightred,Rectangle[{0,0}],lightblue,Rectangle[{1/3,1/3}]}]

Partially overlapping squares with colours which are lighter due to transparency:

Graphics[{Opacity[0.5],lightred,Rectangle[{0,0}],Opacity[0.5],lightblue,Rectangle[{1/3,1/3}]}]

The colours and their darker versions compensated for transparency:

lightred
compensateTransparency[lightred,0.5]

lightblue
compensateTransparency[lightblue,0.5]

With transparency added, they look like the original colours:

Graphics[{Opacity[0.5],compensateTransparency[lightred,0.5],Rectangle[{0,0}],Opacity[0.5],compensateTransparency[lightblue,0.5],Rectangle[{1/3,1/3}]}]

With a too small opacity, the transparency cannot be compensated for for one or more colour components:

compensateTransparency[lightblue,0.2]