SIMEL
SIMEL

Reputation: 8939

Manipulating color in Tcl

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.

Upvotes: 2

Views: 2164

Answers (2)

Keith
Keith

Reputation: 673

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%."

Upvotes: 1

Donal Fellows
Donal Fellows

Reputation: 137707

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)}]]
}

Upvotes: 3

Related Questions