Mercurial > parpg-source
comparison bGrease/color.py @ 41:ff3e395abf91
Renamed grease to bGrease (Basic Grease) to get rid of conflicts with an already installed grease.
author | KarstenBock@gmx.net |
---|---|
date | Mon, 05 Sep 2011 15:00:34 +0200 |
parents | grease/color.py@bc88f7d5ca8b |
children | a6bbb732b27b |
comparison
equal
deleted
inserted
replaced
40:2e3ab06a2f47 | 41:ff3e395abf91 |
---|---|
1 | |
2 class RGBA(object): | |
3 """Four channel color representation. | |
4 | |
5 RGBA colors are floating point color representations with color channel | |
6 values between (0..1). Colors may be initialized from 3 or 4 floating | |
7 point numbers or a hex string:: | |
8 | |
9 RGBA(1.0, 1.0, 1.0) # Alpha defaults to 1.0 | |
10 RGBA(1.0, 1.0, 0, 0.5) | |
11 RGBA("#333") | |
12 RGBA("#7F7F7F") | |
13 | |
14 Individual color channels can be accessed by attribute name, or the | |
15 color object can be treated as a sequence of 4 floats. | |
16 """ | |
17 | |
18 def __init__(self, r_or_colorstr, g=None, b=None, a=None): | |
19 if isinstance(r_or_colorstr, str): | |
20 assert g is b is a is None, "Ambiguous color arguments" | |
21 self.r, self.g, self.b, self.a = self._parse_colorstr(r_or_colorstr) | |
22 elif g is b is a is None: | |
23 try: | |
24 self.r, self.g, self.b, self.a = r_or_colorstr | |
25 except ValueError: | |
26 self.r, self.g, self.b = r_or_colorstr | |
27 self.a = 1.0 | |
28 else: | |
29 self.r = r_or_colorstr | |
30 self.g = g | |
31 self.b = b | |
32 self.a = a | |
33 if self.a is None: | |
34 self.a = 1.0 | |
35 | |
36 def _parse_colorstr(self, colorstr): | |
37 length = len(colorstr) | |
38 if not colorstr.startswith("#") or length not in (4, 5, 7, 9): | |
39 raise ValueError("Invalid color string: " + colorstr) | |
40 if length <= 5: | |
41 parsed = [int(c*2, 16) / 255.0 for c in colorstr[1:]] | |
42 else: | |
43 parsed = [int(colorstr[i:i+2], 16) / 255.0 for i in range(1, length, 2)] | |
44 if len(parsed) == 3: | |
45 parsed.append(1.0) | |
46 return parsed | |
47 | |
48 def __len__(self): | |
49 return 4 | |
50 | |
51 def __getitem__(self, item): | |
52 return (self.r, self.g, self.b, self.a)[item] | |
53 | |
54 def __iter__(self): | |
55 return iter((self.r, self.g, self.b, self.a)) | |
56 | |
57 def __eq__(self, other): | |
58 return tuple(self) == tuple(other) | |
59 | |
60 def __repr__(self): | |
61 return "%s(%.2f, %.2f, %.2f, %.2f)" % (self.__class__.__name__, | |
62 self.r, self.g, self.b, self.a) | |
63 | |
64 |