Version 0 of Drawing Gradients on a Canvas

Updated 2002-12-25 06:47:39

GPS: This code draws gradients that look like the image below.

 [todo making screenshot, please don't edit yet.]




  proc + {n1 n2} {
    expr {$n1 + $n2}
  }
  proc - {n1 n2} {
    expr {$n1 - $n2}
  }
  proc * {n1 n2} {
    expr {$n1 * $n2}
  }
  proc / {n1 n2} {
    expr {$n1 / $n2}
  }
  proc toInt {n} {
    expr int($n)
  }

  proc drawGradient {win type col1Str col2Str} {
    $win delete gradient

    set width [winfo width $win]
    set height [winfo height $win]

    foreach {r1 g1 b1} [winfo rgb $win $col1Str] break
    foreach {r2 g2 b2} [winfo rgb $win $col2Str] break

    set rRange [- $r2.0 $r1]
    set rRatio [/ $rRange $width]

    set gRange [- $g2.0 $g1]
    set gRatio [/ $gRange $width]

    set bRange [- $b2.0 $b1]
    set bRatio [/ $bRange $width]

    if {$type == "x"} {
      for {set x 0} {$x < $width} {incr x} {
        set nR [toInt [+ $r1 [* $rRatio $x]]]
        set nG [toInt [+ $g1 [* $gRatio $x]]]
        set nB [toInt [+ $b1 [* $bRatio $x]]]

        set col [format {%4.4x} $nR]
        append col [format {%4.4x} $nG]
        append col [format {%4.4x} $nB]
        $win create line $x 0 $x $height -tags gradient -fill #${col}
      }
    } else {
      for {set y 0} {$y < $height} {incr y} {
        set nR [toInt [+ $r1 [* $rRatio $y]]]
        set nG [toInt [+ $g1 [* $gRatio $y]]]
        set nB [toInt [+ $b1 [* $bRatio $y]]]

        set col [format {%4.4x} $nR]
        append col [format {%4.4x} $nG]
        append col [format {%4.4x} $nB]
        $win create line 0 $y $width $y -tags gradient -fill #${col}
      }
    }
    return $win
  }

  canvas .grad1
  bind .grad1 <Configure> [list drawGradient .grad1 x red royalblue]

  canvas .grad2
  bind .grad2 <Configure> [list drawGradient .grad2 x yellow red]

  pack .grad1 .grad2 -fill both -expand 1