aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/reading/component/style/Color.scala
blob: ed2041fb59e8ecac5db110be9f57da04138bed4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package reading.component.style

import scala.util.Try

import scalacss.internal.{ ValueT, Color => ScalaCssColor }

case class Color(red: Int, green: Int, blue: Int, alpha: Double = 1.0) {
  val value: ValueT[ValueT.Color] = ScalaCssColor.rgba(red, green, blue, alpha)

  def lighten(pct: Int): Color = ratio(1.0 + pct / 100.0)
  def darken(pct: Int): Color = ratio(1.0 - pct / 100.0)

  private def ratio(r: Double): Color =
    Color(
      red = Color.bound(red * r),
      green = Color.bound(green * r),
      blue = Color.bound(blue * r),
      alpha = alpha
    )
}

// http://chir.ag/projects/name-that-color
object Color {
  val black = Color.fromHex("#000000")
  val mickado = Color.fromHex("#2D2510")
  val white = Color.fromHex("#FFFFFF")
  val gray = Color.fromHex("#808080")
  val eastBay = Color.fromHex("#505080")
  val congoBrown = Color.fromHex("#57363E")
  val stiletto = Color.fromHex("#9C3336")
  val englishWalnut = Color.fromHex("#3F2626")

  def fromHex(hex: String, alpha: Double = 1.0) =
    Color(
      red = Try(Integer.parseInt(hex.slice(1, 3), 16)).getOrElse(0),
      green = Try(Integer.parseInt(hex.slice(3, 5), 16)).getOrElse(0),
      blue = Try(Integer.parseInt(hex.slice(5, 7), 16)).getOrElse(0),
      alpha = alpha
    )

  def bound(n: Int): Int = Math.max(0, Math.min(255, n))
  def bound(d: Double): Int = bound(d.toInt)
}