Dan Sandler | 45f17c5 | 2018-05-02 20:01:38 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2018 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package com.android.egg.paint |
| 18 | |
| 19 | import android.graphics.Color |
| 20 | |
| 21 | class Palette { |
| 22 | var colors : IntArray |
| 23 | var lightest = 0 |
| 24 | var darkest = 0 |
| 25 | |
| 26 | /** |
| 27 | * rough luminance calculation |
| 28 | * https://www.w3.org/TR/AERT/#color-contrast |
| 29 | */ |
| 30 | private fun lum(rgb: Int): Float { |
| 31 | return (Color.red(rgb) * 299f + Color.green(rgb) * 587f + Color.blue(rgb) * 114f) / 1000f |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * create a random evenly-spaced color palette |
| 36 | * guaranteed to contrast! |
| 37 | */ |
| 38 | fun randomize(S: Float, V: Float) { |
| 39 | val hsv = floatArrayOf((Math.random() * 360f).toFloat(), S, V) |
| 40 | val count = colors.size |
| 41 | colors[0] = Color.HSVToColor(hsv) |
| 42 | lightest = 0 |
| 43 | darkest = 0 |
| 44 | |
| 45 | for (i in 0 until count) { |
| 46 | hsv[0] = (hsv[0] + 360f / count).rem(360f) |
| 47 | val color = Color.HSVToColor(hsv) |
| 48 | colors[i] = color |
| 49 | |
| 50 | val lum = lum(colors[i]) |
| 51 | if (lum < lum(colors[darkest])) darkest = i |
| 52 | if (lum > lum(colors[lightest])) lightest = i |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | override fun toString() : String { |
| 57 | val str = StringBuilder("Palette{ ") |
| 58 | for (c in colors) { |
| 59 | str.append(String.format("#%08x ", c)) |
| 60 | } |
| 61 | str.append("}") |
| 62 | return str.toString() |
| 63 | } |
| 64 | |
| 65 | constructor(count: Int) { |
| 66 | colors = IntArray(count) |
| 67 | randomize(1f, 1f) |
| 68 | } |
| 69 | |
| 70 | constructor(count: Int, S: Float, V: Float) { |
| 71 | colors = IntArray(count) |
| 72 | randomize(S, V) |
| 73 | } |
| 74 | |
| 75 | constructor(_colors: IntArray) { |
| 76 | colors = _colors |
| 77 | for (i in 0 until colors.size) { |
| 78 | val lum = lum(colors[i]) |
| 79 | if (lum < lum(colors[darkest])) darkest = i |
| 80 | if (lum > lum(colors[lightest])) lightest = i |
| 81 | } |
| 82 | } |
| 83 | } |