KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > util > ColorRange


1 package org.snipsnap.util;
2
3 /**
4  * Generates a range of HTML compatible colors from start to end
5  *
6  * @author stephan
7  * @version $Id: ColorRange.java 242 2002-08-08 14:49:39Z stephan $
8  **/

9
10 public class ColorRange {
11   String JavaDoc start;
12   String JavaDoc end;
13   int steps;
14
15   float dr, dg, db;
16   int r1, g1, b1;
17
18   public ColorRange(String JavaDoc start, String JavaDoc end, int steps) {
19     start = start.substring(0, 1).equals("#") ? start.substring(1) : start;
20     end = end.substring(0, 1).equals("#") ? end.substring(1) : end;
21     this.start = start;
22     this.end = end;
23     this.steps = steps;
24
25     this.r1 = Integer.parseInt(start.substring(0, 2), 16);
26     this.g1 = Integer.parseInt(start.substring(2, 4), 16);
27     this.b1 = Integer.parseInt(start.substring(4, 6), 16);
28
29     int r2 = Integer.parseInt(end.substring(0, 2), 16);
30     int g2 = Integer.parseInt(end.substring(2, 4), 16);
31     int b2 = Integer.parseInt(end.substring(4, 6), 16);
32     if (steps != 1) {
33       this.dr = (r2 - r1) / (steps - 1);
34       this.dg = (g2 - g1) / (steps - 1);
35       this.db = (b2 - b1) / (steps - 1);
36     } else {
37       this.dr = this.dg = this.db = 0;
38     }
39   }
40
41   public String JavaDoc getColor(int step) {
42     if (step > this.steps - 1) {
43       throw new IllegalArgumentException JavaDoc("steps range from 0 to " + (this.steps - 1));
44     }
45
46     int r = (int) (dr * step + r1);
47     int g = (int) (dg * step + g1);
48     int b = (int) (db * step + b1);
49
50     return "#" + Integer.toHexString(r) + Integer.toHexString(g) + Integer.toHexString(b);
51   }
52
53 }
54
Popular Tags