2

I am writing a GTK+ application that is using Pango text attributes to determine the color and other aspects of the text written onto a GtkLabel using something like this:

attributes = pango_attr_list_new();
pango_attr_list_insert(attributes, pango_attr_foreground_new( G_MAXUINT16, G_MAXUINT16, G_MAXUINT16));
pango_attr_list_insert(attributes, pango_attr_size_new (18 * PANGO_SCALE));
pango_attr_list_insert(attributes, pango_attr_weight_new( PANGO_WEIGHT_BOLD ));

lblTotalCredits = gtk_label_new(NULL);
gtk_label_set_text(GTK_LABEL(lblTotalCredits),"0");
gtk_label_set_attributes(GTK_LABEL(lblTotalCredits), attributes);

pango_attr_foreground_new() expects each color component ( R,G,B ) to by 16 bits. Using Photoshop or other image processing tools I can find the color I want to use, but the R,G,B values are displayed as 8 bit R,G,B components.

How do I convert the 8 bit R,G,B values to the equivalent 16 bit R,G,B values so I end up with the same color?

For example, a golden color is specified as RGB ( 229, 202, 115 ) or hex e5ca73. How do I convert that so that each color component is 16 bits for pango functions?

Chimera
  • 5,884
  • 7
  • 49
  • 81

1 Answers1

3

8bit max: 0xFF
16bit max: 0xFFFF

convert (I use red as a demo) (untested):

guint32 colorhex = 0xe5ca73;
const guint8 red8 = (guint8)((colorhex & 0xFF0000) >> 16);
//    guint16 red16 = (guint16)(((guint32)(r * 0xFFFF / 0xFF)) & 0xFFFF);
guint16 red16 = ((guint16)red8 << 8) | red8;
drahnr
  • 6,782
  • 5
  • 48
  • 75
  • You know that shiny green accept button ;) Corrected: guint is way better – drahnr Aug 20 '12 at 19:18
  • Oh no worries, I will be accepting your answer! I'm just waiting to see if I get some upvotes on my question, or other answers. – Chimera Aug 20 '12 at 19:21
  • Last step seems overly complicated...you can just duplicate the 8 bit color component like this: red16 = red8*256u+red8 – ergosys Aug 21 '12 at 01:35
  • Now that you say it, `red16 = ((guint16)red8)<<8 + red8` would be even better – drahnr Aug 21 '12 at 07:15
  • I don't understand why you want to use the 8 bits value in the lower bits instead of leaving zeroes. This all looks overly complicated. – liberforce Aug 21 '12 at 09:01
  • Because then the colours would all be a bit darker than expected – drahnr Aug 21 '12 at 15:09
  • @drahnr, I'm not really seeing how that expression is better. It's logically equivalent, but it has more parentheses. – ergosys Aug 21 '12 at 23:29
  • The parenthesis and casting are just there to make it easy to copy&paste and derive a define from that with maximum possible compiler info on missusage. And I like bitshifting, it is more clear in this case. – drahnr Aug 21 '12 at 23:34
  • 1
    `(red8 << 8) & red8` is wrong. You should have written `(red8 << 8) | red8`. – liberforce Aug 22 '12 at 11:21