Titanium app hex color value with alpha channel
On 7 November 2014 in TechColor values are represented in hexadecimal value:
#000000
- 0 – red, 0 – green, 0 – blue
- color = black
#ffffff
- 255 – red, 255 – green, 255 – blue
- color = white
‘ff’ in hexadecimal is 255 in decimal, (2 ^ 8) – 1 = 255.
In CSS, to represent color with alpha channel, we can use the rgba() syntax:
rgba(0, 0, 0, 0.6)
- 0 – red, 0 – green, 0 – blue
- black with 60% opacity
In Titanium, rgba() syntax only available on iOS, but hex value also can be used to represent alpha channel, and it supported by both iOS & Android
#ff000000
- 0 – red, 0 – green, 0 – blue
- ff – 255 /Â 100% opacity
#90ffcc00
- 255 – red, 204 – green, 0 – blue
- 90 – 144 / 56% opacity
To easily maintain colors in app, this function is to transform rgba value into Titanium hex color format
function rgbaToHex(r, g, b, a) { var toHex = function(n) { return ('00' + (n | 0).toString(16)).slice(-2); }; return '#' + toHex(((a * 100) / 100) * 255) + toHex(r) + toHex(g) + toHex (b); }
Explanation:
(n | 0)
is shortcut forparseInt()
, to ensure the value passed in is integer. We don’t want the hex color value to have decimal point, e.g: #2.4ccc.toString(16)
is Number object function (not Object.toString()) to convert number into hexadecimal format('00' + value).slice(-2)
is to add string padding to the left of the string, so that it will always have 2 characters. We don’t want the value to have one character, #0ccff is invalid value
Usage:
var view = Ti.UI.createView({ backgroundColor: rgbaToHex(255, 204, 0, 0.5) });
Related posts:
-
Efficient code
-
Titanium Android keystore
-
ScrollableView in ListView
-
Ti.Network.registerForPushNotifications no response
-
Add project as library – Titanium module (Android)
-
Load nib file in Titanium module iOS
-
Android Progress Notification module
-
Android BOOT_COMPLETED handler module
-
Check if iOS app is connected to VPN
-
Webview evalJS return null in Android 4.2.2
Filed under Tech with tags Android, Hex color, Hex value, iOS, Javascript, Titanium Mobile
Leave a Reply