颜色值如何使用 C++ 输出字符串格式?
//https://developer.android.com/reference/android/graphics/Color.html
//https://en.wikipedia.org/wiki/RGBA_color_model#Representation
union Color32
{
unsigned int color;
struct RGBA{ unsigned char r, g, b, a; } rgba;
struct ARGB{ unsigned char a, r, g, b; } argb;//
std::string toString() {
std::string rgba = "#";
rgba += n2hexstr<int>((int)this->argb.r,2);
rgba += n2hexstr<int>((int)this->argb.g,2);
rgba += n2hexstr<int>((int)this->argb.b,2);
rgba += n2hexstr<int>((int)this->argb.a,2);
return rgba;
}
private:
template <typename I> std::string n2hexstr(I w, size_t hex_len = sizeof(I) << 1) {
static const char* digits = "0123456789ABCDEF";
std::string rc(hex_len, '0');
for (size_t i = 0, j = (hex_len - 1) * 4; i < hex_len; ++i, j -= 4)
rc[i] = digits[(w >> j) & 0x0f];
return rc;
}
};
std::ostream& operator << (std::ostream& dbg, const Color32::RGBA& obj) {
dbg << "r=" << (int)obj.r << " "
<< "g=" << (int)obj.g << " "
<< "b=" << (int)obj.b << " "
<< "a=" << (int)obj.a << " ";
return dbg;
}
std::ostream& operator << (std::ostream& dbg, const Color32::ARGB& obj) {
dbg << "a=" << (int)obj.a << " "
<< "r=" << (int)obj.r << " "
<< "g=" << (int)obj.g << " "
<< "b=" << (int)obj.b << " ";
return dbg;
}
std::ostream& operator << (std::ostream& dbg, const Color32& obj) {
int color = obj.color;
int A = (color >> 24) & 0xff; // or color >> 24
int R = (color >> 16) & 0xff;
int G = (color >> 8) & 0xff;
int B = (color) & 0xff;
dbg << " A=" << A << " R=" << R << " G=" << G << " B=" << B << " ";
dbg << "color=" << obj.color << "\t" << obj.rgba << "\t" << obj.argb;
return dbg;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)