Skip to content

Commit fe93b3d

Browse files
committed
Updated and extended the Color class
1 parent 053d5c2 commit fe93b3d

1 file changed

Lines changed: 38 additions & 5 deletions

File tree

src/core/modules/basetypes/basetypes_wrap_python.cpp

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,23 +89,56 @@ void export_interval()
8989
//-----------------------------------------------------------------------------
9090
// Expose Color.
9191
//-----------------------------------------------------------------------------
92+
class ColorExt
93+
{
94+
public:
95+
static Color WithAlpha(const Color& color, unsigned char a)
96+
{
97+
return Color(color.r(), color.g(), color.b(), a);
98+
}
99+
100+
static str GetHexString(const Color& color)
101+
{
102+
char buffer[10];
103+
if (color.a() == 255)
104+
sprintf(buffer, "\x07%02X%02X%02X", color.r(), color.g(), color.b());
105+
else
106+
sprintf(buffer, "\x08%02X%02X%02X%02X", color.r(), color.g(), color.b(), color.a());
107+
108+
return str(buffer);
109+
}
110+
};
111+
92112
void export_color()
93113
{
94-
class_<Color, Color *> Color_("Color");
95-
96-
// Initializers...
97-
Color_.def(init<int, int, int, optional<int>>());
98-
114+
class_<Color, Color *> Color_(
115+
"Color",
116+
init<unsigned char, unsigned char, unsigned char, unsigned char>(
117+
(arg("r")=0, arg("g")=0, arg("b")=0, arg("a")=255)
118+
)
119+
);
99120

100121
// Properties...
101122
Color_.add_property("r", &Color::r, &IndexSetter<Color, unsigned char, 0>);
102123
Color_.add_property("g", &Color::g, &IndexSetter<Color, unsigned char, 1>);
103124
Color_.add_property("b", &Color::b, &IndexSetter<Color, unsigned char, 2>);
104125
Color_.add_property("a", &Color::a, &IndexSetter<Color, unsigned char, 3>);
105126

127+
// Methods
128+
Color_.def(
129+
"with_alpha",
130+
ColorExt::WithAlpha,
131+
"Returns a copy of the color with a new alpha value."
132+
);
133+
106134
// Special methods...
107135
Color_.def("__getitem__", &GetItemIndexer<Color, unsigned char, 0, 3>);
108136
Color_.def("__setitem__", &SetItemIndexer<Color, unsigned char, 0, 3>);
137+
Color_.def(
138+
"__str__",
139+
&ColorExt::GetHexString,
140+
"Returns the color as a hex string."
141+
);
109142

110143
// Operators...
111144
Color_.def(self == self);

0 commit comments

Comments
 (0)