Skip to content

Instantly share code, notes, and snippets.

@dkuku
Last active April 6, 2019 11:32
Show Gist options
  • Save dkuku/48eb27e09af8c966c83489c5ba42d75b to your computer and use it in GitHub Desktop.
Save dkuku/48eb27e09af8c966c83489c5ba42d75b to your computer and use it in GitHub Desktop.
def alpha(color, background="#FFFFFF"):
def split_rgba(color):
#return tuple of integers
#strip hash from the beginning if exist
if color[0] == "#":
color = color[1:]
if len(color) in [3,4]:
R = color[0] * 2
G = color[1] * 2
B = color[2] * 2
if len(color) == 4:
A = color[3] * 2
else:
A = "00"
if len(color) in [6,8]:
R = color[ :2]
G = color[2:4]
B = color[4:6]
if len(color) == 8:
A = color[6: ]
else:
A = "00"
return (int("0x" + x, 16) for x in (R,G,B,A))
def int2hex(i):
#convert to hex and cut trailing "0x"
value = hex(int(i))[2:]
if len(value) == 1:
return "0" + value
return value
def alpha_blend(color, background, alpha ):
#return calculated color
new_color = background * (0xFF-alpha)/0xFF + color * alpha/0xFF
return int2hex(new_color)
R,G,B,A = split_rgba(color)
r,g,b,a = split_rgba(background)
R = alpha_blend(R,r,A)
G = alpha_blend(G,g,A)
B = alpha_blend(B,b,A)
return f"#{R}{G}{B}"
import unittest
class TestAplhaBlend(unittest.TestCase):
def test_total_transparent(self):
self.assertEqual(alpha("#12345600"), "#ffffff")
self.assertEqual(alpha("#11111100"), "#ffffff")
self.assertEqual(alpha("#FFFFFF00"), "#ffffff")
def test_total_transparent_with_background(self):
self.assertEqual(alpha("#00000000", "#000"), "#000000")
self.assertEqual(alpha("#00000000", "#fff"), "#ffffff")
self.assertEqual(alpha("#00000000", "#555555"), "#555555")
self.assertEqual(alpha("#55555500", "#ffff"), "#ffffff")
def test_total_opaque(self):
self.assertEqual(alpha("#000000FF"), "#000000")
self.assertEqual(alpha("#FFFFFFFF"), "#ffffff")
self.assertEqual(alpha("#123456FF"), "#123456")
def test_total_opaque_with_background(self):
self.assertEqual(alpha("#654321ff", "#000000"), "#654321")
self.assertEqual(alpha("#654321ff", "#123456"), "#654321")
self.assertEqual(alpha("#654321ff", "#ffffff"), "#654321")
self.assertEqual(alpha("#ffffffff", "#000000"), "#ffffff")
self.assertEqual(alpha("#000000ff", "#000000"), "#000000")
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment