Paste #3tW -- näytä pelkkänä tekstinä -- uusi tämän pohjalta
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | #include <string> #include <iostream> #include <irrlicht.h> #include <assert.h> using namespace irr; #define errorstream std::cerr static inline bool hex_digit_decode(char hexdigit, unsigned char &value) { if(hexdigit >= '0' && hexdigit <= '9') value = hexdigit - '0'; else if(hexdigit >= 'A' && hexdigit <= 'F') value = hexdigit - 'A' + 10; else if(hexdigit >= 'a' && hexdigit <= 'f') value = hexdigit - 'a' + 10; else return false; return true; } bool parseColor(const std::string &value, video::SColor &color, bool quiet) { const char *hexpattern = NULL; if (value[0] == '#') { if (value.size() == 9) hexpattern = "#RRGGBBAA"; else if (value.size() == 7) hexpattern = "#RRGGBB"; else if (value.size() == 5) hexpattern = "#RGBA"; else if (value.size() == 4) hexpattern = "#RGB"; } if (hexpattern) { assert(strlen(hexpattern) == value.size()); video::SColor outcolor(255, 255, 255, 255); for (size_t pos = 0; pos < value.size(); ++pos) { // '#' in the pattern means skip that character if (hexpattern[pos] == '#') continue; // Else assume hexpattern[pos] is one of 'R' 'G' 'B' 'A' // Read one or two digits, depending on hexpattern unsigned char c1, c2; if (hexpattern[pos+1] == hexpattern[pos]) { // Two digits, e.g. hexpattern == "#RRGGBB" if (!hex_digit_decode(value[pos], c1) || !hex_digit_decode(value[pos+1], c2)) goto fail; ++pos; } else { // One digit, e.g. hexpattern == "#RGB" if (!hex_digit_decode(value[pos], c1)) goto fail; c2 = c1; } u32 colorpart = ((c1 & 0x0f) << 4) | (c2 & 0x0f); // Update outcolor with newly read color part if (hexpattern[pos] == 'R') outcolor.setRed(colorpart); else if (hexpattern[pos] == 'G') outcolor.setGreen(colorpart); else if (hexpattern[pos] == 'B') outcolor.setBlue(colorpart); else if (hexpattern[pos] == 'A') outcolor.setAlpha(colorpart); } color = outcolor; return true; } // Optionally, named colors could be implemented here fail: if (!quiet) errorstream<<"Invalid color: \""<<value<<"\""<<std::endl; return false; } void dumpColor(video::SColor color) { std::cout<<"R="<<color.getRed()<<" G="<<color.getGreen() <<" B="<<color.getBlue()<<" A="<<color.getAlpha()<<std::endl; } int main(void) { video::SColor color(1, 2, 3, 4); parseColor("#c0ffee", color, false); dumpColor(color); parseColor("#406082a0", color, false); dumpColor(color); parseColor("#0dd", color, false); dumpColor(color); parseColor("#affe", color, false); dumpColor(color); return 0; } |