Adding Transparent Background to Your Views

When you’re working with views, at some point you’ll need to add some transparency to the background, for example if you have text on top of an image and you want to make sure the text is readable. This was the case of the PhotoMEME app that I explained how to build in my book Build native cross-platform apps with Appcelerator.

Regular solid backgrounds are applied by using the RGB value, either in its HEX format, such as #FF0000 for red, or as Red, Green and Blue values like rgb(255,0,0).

Now, to make a red background transparent you use RGBA, where the A stands for the Alpha Channel. Hence, to apply a red background with 50% transparency on iOS, you do something like:

    backgroundColor : rgba(255,0,0,0.5)

Notice the emphasis on iOS, and the reason is because Android works a bit different. On iOS you specify the Alpha Channel as a number between 0 and 1, 0.5 being 50%. On Android however, the Alpha Channel is specified as a number between 0 and 255. So for Android, you’d use something like:

    backgroundColor : rgba(255,0,0,127)

Now, there’s a cross-platform way of achieving this, and that is by using ARGB (notice the Alpha Channel in the front). To use ARGB, you use HEX triplets just like HTML, so for red you’d use something like:

    backgroundColor : "#80FF0000"

In the code above above I’m using the typical HEX triplet for red which is FF0000, but I’m adding 80 to the front of it, which is the representation of 50%. There’s a mathematical formula for converting 50% to HEX, but I think it’s irrelevant – The important thing is to be able to express your percentage of opacity as HEX, and for this you could use the following table.

Alpha Level HEX Code
100% FF
95% F2
90% E6
85% D9
80% CC
75% BF
70% B3
65% A6
60% 99
55% 8C
50% 80
45% 73
40% 66
35% 59
30% 4D
25% 40
20% 33
15% 26
10% 1A
5% 0D
0% 00

To learn more about this and other cool cross-platform tips, tricks, techniques and full apps, make sure you checkout my book Build native cross-platform apps with Appcelerator.



[Editor’s Note:   This post was updated by Brenton House in June 2019]


    • Hi Nico. Yes, you could use the opacity property together with background color. This method takes care of both properties at once, but the result is essentially the same.

  1. One thing I’ve noticed while using the ‘opacity’ property, is that all the children of the view inherit the opacity of their parent.

    If I use the above trick with the backgroundColor, like “#80FF0000”. Will the children of this view inherit the opacity of 50%?

Comments are closed.