Back to index

nux  3.0.0
ColorPrivate.cpp
Go to the documentation of this file.
00001 /*
00002  * Copyright 2012 Inalogic® Inc.
00003  *
00004  * This program is free software: you can redistribute it and/or modify it
00005  * under the terms of the GNU Lesser General Public License, as
00006  * published by the  Free Software Foundation; either version 2.1 or 3.0
00007  * of the License.
00008  *
00009  * This program is distributed in the hope that it will be useful, but
00010  * WITHOUT ANY WARRANTY; without even the implied warranties of
00011  * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR
00012  * PURPOSE.  See the applicable version of the GNU Lesser General Public
00013  * License for more details.
00014  *
00015  * You should have received a copy of both the GNU Lesser General Public
00016  * License along with this program. If not, see <http://www.gnu.org/licenses/>
00017  *
00018  * Authored by: Andrea Azzarone <azzaronea@gmail.com>
00019  *
00020  */
00021 
00022 #include <sstream>
00023 
00024 #include "ColorPrivate.h"
00025 
00026 namespace nux
00027 {
00028 namespace color
00029 {
00030 
00031 bool IsValidHex(std::string hex)
00032 {
00033   static const std::string allowed_chars("0123456789abcdefABCDEF");
00034 
00035   if (hex.empty())
00036     return false;
00037 
00038   if (hex[0] == '#')
00039     hex.erase(hex.begin());
00040 
00041   switch (hex.length())
00042   {
00043     case 3: // #rgb
00044     case 4: // #rgba
00045     case 6: // #rrggbb
00046     case 8: // #rrggbbaa
00047       return (hex.find_first_not_of(allowed_chars) == hex.npos);
00048     default:
00049       return false;
00050   }
00051 }
00052 
00053 
00054 int HexToInt(std::string const& hex)
00055 {
00056   std::istringstream istr(hex);
00057   int ret;
00058   istr >> std::hex >> ret;
00059 
00060   return ret;
00061 }
00062 
00063 
00064 bool HexToRGBA(std::string hex, float& r, float& g, float& b, float& a)
00065 {
00066   if (!IsValidHex(hex))
00067     return false;
00068 
00069   if (hex[0] == '#')
00070     hex.erase(hex.begin());
00071 
00072   a = 1.0f;
00073 
00074   if (hex.length() == 3 || hex.length() == 4)
00075   {
00076     r = HexToInt(hex.substr(0, 1) + hex.substr(0, 1)) / 255.0f;
00077     g = HexToInt(hex.substr(1, 1) + hex.substr(1, 1)) / 255.0f;
00078     b = HexToInt(hex.substr(2, 1) + hex.substr(2, 1)) / 255.0f;
00079 
00080     if (hex.length() == 4)
00081       a = HexToInt(hex.substr(3, 1) + hex.substr(3, 1)) / 255.0f;
00082   }
00083   else if (hex.length() == 6 || hex.length() == 8)
00084   {
00085     r = HexToInt(hex.substr(0, 2)) / 255.0f;
00086     g = HexToInt(hex.substr(2, 2)) / 255.0f;
00087     b = HexToInt(hex.substr(4, 2)) / 255.0f;
00088 
00089     if (hex.length() == 8)
00090       a = HexToInt(hex.substr(6, 2)) / 255.0f;
00091   }
00092 
00093   return true;
00094 }
00095 
00096 } // namespace color
00097 } // namespace nux
00098