OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 /// Utility library for creating web colors. |
| 6 |
| 7 library colors; |
| 8 |
| 9 /// A web color. |
| 10 abstract class Color { |
| 11 /// The hexadecimal code for the color, without the prefixed '#'. |
| 12 String get toHex; |
| 13 } |
| 14 |
| 15 /// A web color defined as RGB. |
| 16 class RGB implements Color { |
| 17 final double r; |
| 18 final double g; |
| 19 final double b; |
| 20 |
| 21 /// Creates a color defined by the amount of red [r], green [g], and blue [b] |
| 22 /// all in range 0..1. |
| 23 const RGB(this.r, this.g, this.b); |
| 24 |
| 25 String get toHex { |
| 26 StringBuffer sb = new StringBuffer(); |
| 27 |
| 28 void writeHex(double value) { |
| 29 int i = (value * 255.0).round(); |
| 30 if (i < 16) { |
| 31 sb.write('0'); |
| 32 } |
| 33 sb.write(i.toRadixString(16)); |
| 34 } |
| 35 |
| 36 writeHex(r); |
| 37 writeHex(g); |
| 38 writeHex(b); |
| 39 |
| 40 return sb.toString(); |
| 41 } |
| 42 |
| 43 String toString() => 'rgb($r,$g,$b)'; |
| 44 } |
| 45 |
| 46 /// A web color defined as HSV. |
| 47 class HSV implements Color { |
| 48 final double h; |
| 49 final double s; |
| 50 final double v; |
| 51 |
| 52 /// Creates a color defined by the hue [h] in range 0..360 (360 excluded), |
| 53 /// saturation [s] in range 0..1, and value [v] in range 0..1. |
| 54 const HSV(this.h, this.s, this.v); |
| 55 |
| 56 String get toHex => toRGB(this).toHex; |
| 57 |
| 58 static RGB toRGB(HSV hsv) { |
| 59 double h = hsv.h; |
| 60 double s = hsv.s; |
| 61 double v = hsv.v; |
| 62 if (s == 0.0) { |
| 63 // Grey. |
| 64 return new RGB(v, v, v); |
| 65 } |
| 66 h /= 60.0; // Sector 0 to 5. |
| 67 int i = h.floor(); |
| 68 double f = h - i; // Factorial part of [h]. |
| 69 double p = v * (1.0 - s); |
| 70 double q = v * (1.0 - s * f); |
| 71 double t = v * (1.0 - s * (1.0 - f )); |
| 72 switch (i) { |
| 73 case 0: |
| 74 return new RGB(v, t, p); |
| 75 case 1: |
| 76 return new RGB(q, v, p); |
| 77 case 2: |
| 78 return new RGB(p, v, t); |
| 79 case 3: |
| 80 return new RGB(p, q, v); |
| 81 case 4: |
| 82 return new RGB(t, p, v); |
| 83 default: // case 5: |
| 84 return new RGB(v, p, q); |
| 85 } |
| 86 } |
| 87 |
| 88 String toString() => 'hsv($h,$s,$v)'; |
| 89 } |
OLD | NEW |