OK, I've tidied up my first draft and added a little Tk testing toy. The contrasting colours returned tend toward the lighter but the hash is easily tweaked.
#! perl
use strict;
use warnings;
use Tk;
my $title = "colour contrast";
my $mw = new MainWindow( -title => $title );
my $fr = $mw->Frame()->pack;
for ( 1 .. 5 ) {
my $b = $fr->Button( -text => "Colour $_", )->pack;
$b->configure( -command => [ \&pick_n_mix, $b ] );
}
MainLoop();
sub pick_n_mix {
my ($btn) = @_;
my $old = $btn->cget( -bg );
my $col = $mw->chooseColor(
-title => "Choose a nice colour...",
-initialcolor => $old
);
return unless $col;
$btn->configure( -bg => $col, -activebackground => $col );
# Choose some contrasting colours...
my $fg = contrast_colour($col);
$btn->configure(
-bg => $col,
-activebackground => $col,
-fg => $fg,
-activeforeground => $fg
);
}
# given a colour in the form "#ff00ff" i.e. hex rrggbb, return a
# contrasting colour
sub contrast_colour {
my $col = shift;
# Need rgb values for colour...
if ( not $col =~ /^#(\w\w)(\w\w)(\w\w)$/ ) {
warn "failed to convert colour '$col' to rgb components\n";
return;
}
my ( $r, $g, $b ) = map hex, ( $1, $2, $3 );
# Use a hash of contrasting values for the "websafe pallette"
# with emphasis on lighter colours...
my %opp = qw(00 FF 33 FF 66 FF 99 FF CC 00 FF 00 );
# Round each value down to a multiple of hex 33 (i.e. 51)...
map { $_ = int( $_ / 51 ) * 51 } ( $r, $g, $b );
# Replace each value with a contrasting value from the hash...
map { $_ = $opp{ sprintf "%02X", $_ } } ( $r, $g, $b );
return "#$r$g$b";
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.