Having "n" number of overlaying channels (bitmaps in the same place, layers etc.) how to calculate required alpha for each of them, so they "hide" background completely?

Each layer can have equal value, sum should be exactly 1 ("full alpha"). "n" is 2 or more (likely up to dozens).

[Game example of this would be a Smoke Grenade in FPS game - multiple ("n") bitmaps, making area behind it completely invisible for player - if standing before smoked area (standing inside results in partly-covered vision).]

  • \$\begingroup\$ If you need to hide something for gameplay reasons, just hide it completely. See this related question, which is about gamma instead of alpha, but the reasons are the same. \$\endgroup\$ – congusbongus Mar 4 '15 at 12:27

Unfortunately, the only way to (theoretically) get stuff to layer together into a full-alpha pixel is to have a completely opaque layer.

Reasoning: The alpha channel is a multiplier for applying the other colour channels. Painting a region with opacity opacity,n times, gives you 1 - opacity^n final alpha.

Here's a demo:

black rectangle with 0.5 opacity, cumulatively added together

The leftmost is black at opacity 0.5. Each consecutive one is one more copy of it stacked on top of it. The opacities are approximately 0.5, 0.75, 0.87, 0.97. They tend toward 1, but won't reach it:

Querying Wolfram Alpha with 1 - 0.5^n:

y = 1 - 0.5^n chart

As n→∞, the function tends toward (but never reaches) 1.

limit of the function

In practice, floating point rounding error would hit at some point due to sometimes unpredictable hardware-dependent limitations.

Even so, 0.9 opacity is probably good enough. Could you tell the difference in a fast-paced game? The right rectangle is actually 0.9 opacity:

left is opacity 1, right is opacity 0.9

We can solve for what value of n would produce 0.9 opacity:

0.9 = 1 - 0.5^n implies n = 3.32193

So for layers with opacity 0.5, four layers should be enough. Try it with your own values.

| improve this answer | |
  • \$\begingroup\$ Great explanation, but how to "invert" this solution, when "n" is known and alpha not? \$\endgroup\$ – madneon Mar 4 '15 at 12:13
  • \$\begingroup\$ @madneon wolframalpha.com/input/?i=0.9+%3D+1+-+x%5E4 \$\endgroup\$ – congusbongus Mar 4 '15 at 12:37
  • \$\begingroup\$ So it comes down to finding log(n)? I've checked it out, and layers adds up to about 0.9 when coded: alpha = 1 / log(n) \$\endgroup\$ – madneon Mar 4 '15 at 13:09

This is the result of 1 / log(n). Using "Double Float" for calculations, alpha values in pictures are rounded to 2 decimal places.

Black on White: Multiple Layers Alpha Addition - Black on White

White on Black: Multiple Layers Alpha Addition - White on Black

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.