eufon

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

color.c (892B)


      1 /* Copyright (c), Niclas Meyer <niclas@countingsort.com>
      2  *
      3  * This Source Code Form is subject to the terms of the Mozilla Public
      4  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
      5  * You can obtain one at https://mozilla.org/MPL/2.0/.
      6  */
      7 
      8 #include "color.h"
      9 
     10 #include <stdint.h>
     11 #include <stdlib.h>
     12 #include <string.h>
     13 
     14 bool
     15 color_parse(const char *hex, float color[static 4])
     16 {
     17     if (hex[0] == '#') {
     18         ++hex;
     19     }
     20 
     21     int len = strlen(hex);
     22     if (len != 6 && len != 8) {
     23         return false;
     24     }
     25 
     26     uint32_t rgba = (uint32_t)strtoul(hex, NULL, 16);
     27     if (len == 6) {
     28         rgba = (rgba << 8) | 0xff;
     29     }
     30 
     31     for (size_t i = 0; i < 4; ++i) {
     32         color[3 - i] = (rgba & 0xff) / 255.0;
     33         rgba >>= 8;
     34     }
     35 
     36     // premultiply alpha
     37     color[0] *= color[3];
     38     color[1] *= color[3];
     39     color[2] *= color[3];
     40 
     41     return true;
     42 }