2

I want to take a color and get a darker color. The color can come in either form that is allowed for colors in Tcl, i.e. blue or #0000FF or any other form that tcl recognizes as a color.

Is there a way to do this?

example of what I need, when I get a color, I want to subtract a constant (or a constant part, i.e. * 0.8) from its red, blue and green values to make it a darker shade of the same color.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
SIMEL
  • 8,745
  • 28
  • 84
  • 130

2 Answers2

3

To get the RGB values for a color, use winfo rgb:

lassign [winfo rgb . $thecolor] r g b

Alas, the values that you get back are in the range 0–65535. When you want to repack them into a parsable color, you need to do some work:

set thecolor [format "#%02x%02x%02x" [expr {$r/256}] [expr {$g/256}] [expr {$b/256}]]

So, to get a darker color, do this:

proc darker {color {ratio 0.8}} {
    lassign [winfo rgb . $color] r g b

    set r [expr {$r * $ratio}]
    set g [expr {$g * $ratio}]
    set b [expr {$b * $ratio}]

    return [format "#%02x%02x%02x" \
            [expr {int($r/256)}] [expr {int($g/256)}] [expr {int($b/256)}]]
}
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
  • Of course, when picking “darker” colors you should arguably work in the HSV colorspace instead of the RGB one, but that's only _really_ necessary when changing hues. – Donal Fellows Sep 15 '13 at 23:05
  • 1
    Does it matter what window I give to the `winfo rgb` command (Where you put `.`)? – SIMEL Sep 16 '13 at 08:01
1

Late to the game, but there's a function build into the standard distribution of Tk that will do this:

::tk::Darken color percent

where color is any valid Tk color name and percent is an "integer telling how much to brighten or darken as a percent: 50 means darken by 50%, 110 means brighten by 10%."

Machavity
  • 30,841
  • 27
  • 92
  • 100
Keith
  • 543
  • 3
  • 8