View Javadoc

1   package net.sf.josceleton.commons.util;
2   
3   import java.awt.Color;
4   
5   /**
6    * @since 0.4
7    */
8   public final class ColorUtil {
9   	
10  	private ColorUtil() {
11  		// utility class is not instantiable
12  	}
13  
14  	/**
15  	 * @since 0.4
16  	 */
17  	public static Color newRandomColor() {
18          final int[] rgb = new int[3];
19          final int rgbIndexSelected = RandomUtil.randFromZeroToExclusive(rgb.length);
20          
21          for (int i = 0; i < rgb.length; i++) {
22                  final int middle;
23                  if(rgbIndexSelected == i) {
24                  	middle = 230;
25                  } else {
26                  	middle = 30;
27                  }
28                  rgb[i] = RandomUtil.generateWithinRange(middle, 20);
29          }
30          
31          return new Color(rgb[0], rgb[1], rgb[2]);
32  	}
33  	
34  	// LUXURY changeBrightness(Color, volume... can be -100 to +100) => internally uses brighten/darken
35  
36  	/**
37  	 * @param volume 0 to 100
38  	 * @since 0.4
39  	 */
40  	public static Color brighten(final Color original, final int volume) {
41          return ColorUtil.changeBrightness(original, volume, true);
42  	}
43  
44  	/**
45  	 * @param volume 0 to 100
46  	 * @since 0.4
47  	 */
48  	public static Color darken(final Color original, final int volume) {
49  		return ColorUtil.changeBrightness(original, volume, false);
50  	}
51  	
52  	private static Color changeBrightness(final Color original, final int volume, final boolean isBrighter) {
53  		final int volumeAdjusted;
54  		final int limit;
55  		if(isBrighter == true) {
56  			volumeAdjusted = volume;
57  			limit = 255;
58  		} else {
59  			volumeAdjusted = -1 * volume;
60  			limit = 0;
61  		}
62  		
63  		final int newR = original.getRed() + volumeAdjusted;
64  		final int newG = original.getGreen() + volumeAdjusted;
65  		final int newB = original.getBlue() + volumeAdjusted;
66  		
67  		return new Color(
68  			MathUtil.checkForMinOrMax(limit, newR, isBrighter),
69  			MathUtil.checkForMinOrMax(limit, newG, isBrighter),
70  			MathUtil.checkForMinOrMax(limit, newB, isBrighter)
71  		);
72  	}
73  }