Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
How do I get a hexadecimal string representation of a GdkRGBA struct in C?
I have a program that reads a hexadecimal string representation from a configuration file, turns it into a GdkRGBA struct from Gdk, uses gtk_color_dialog_button_set_rgba ()
to set it as the default colour of a GtkColorDialogButton, and then listens to user changes to the aforementioned button.
On user change, I want to write back the chosen value to the configuration file so that it is persistent across program launches, and I need it to be a hexadecimal string representation for legacy compatibility reasons (the configuration file is ~/.Xresources
, so it needs to be compatible with many existing programs). However, while Gdk provides a gdk_rgba_parse ()
function to parse a hexadecimal string representation of a colour into a GdkRGBA struct, I can't find anything to do the inverse, i.e., turn a GdkRGBA struct into a hexadecimal string representation. There is gdk_rgba_to_string ()
, but it only returns strings of the form rgb(r,g,b)
or rgba(r,g,b,a)
, whereas I want #rrggbb
.
How can I get the hexadecimal string representation of a GdkRGBA struct's value in C?
1 answer
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
Newbyte | (no comment) | Jan 4, 2025 at 15:59 |
I ended up implementing it like this:
#define RGB_HEX_STRING_LENGTH 8
gchar *
gdkrgba_to_rgb_hex_string (const GdkRGBA *const from)
{
guchar red = roundf (from->red * 255.0f);
guchar green = roundf (from->green * 255.0f);
guchar blue = roundf (from->blue * 255.0f);
gchar *to = malloc (RGB_HEX_STRING_LENGTH);
snprintf (to, RGB_HEX_STRING_LENGTH, "#%02hhx%02hhx%02hhx", red, green, blue);
return to;
}
This works since the properties of the GdkRGBA struct are public, so we can access them directly.
0 comment threads