-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
DynamicTheming.kt
185 lines (170 loc) · 6.52 KB
/
DynamicTheming.kt
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetcaster.util
import android.content.Context
import androidx.collection.LruCache
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.core.graphics.drawable.toBitmap
import androidx.palette.graphics.Palette
import coil.imageLoader
import coil.request.ImageRequest
import coil.request.SuccessResult
import coil.size.Scale
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable
fun rememberDominantColorState(
context: Context = LocalContext.current,
defaultColor: Color = MaterialTheme.colors.primary,
defaultOnColor: Color = MaterialTheme.colors.onPrimary,
cacheSize: Int = 12,
isColorValid: (Color) -> Boolean = { true }
): DominantColorState = remember {
DominantColorState(context, defaultColor, defaultOnColor, cacheSize, isColorValid)
}
/**
* A composable which allows dynamic theming of the [androidx.compose.material.Colors.primary]
* color from an image.
*/
@Composable
fun DynamicThemePrimaryColorsFromImage(
dominantColorState: DominantColorState = rememberDominantColorState(),
content: @Composable () -> Unit
) {
val colors = MaterialTheme.colors.copy(
primary = animateColorAsState(
dominantColorState.color,
spring(stiffness = Spring.StiffnessLow)
).value,
onPrimary = animateColorAsState(
dominantColorState.onColor,
spring(stiffness = Spring.StiffnessLow)
).value
)
MaterialTheme(colors = colors, content = content)
}
/**
* A class which stores and caches the result of any calculated dominant colors
* from images.
*
* @param context Android context
* @param defaultColor The default color, which will be used if [calculateDominantColor] fails to
* calculate a dominant color
* @param defaultOnColor The default foreground 'on color' for [defaultColor].
* @param cacheSize The size of the [LruCache] used to store recent results. Pass `0` to
* disable the cache.
* @param isColorValid A lambda which allows filtering of the calculated image colors.
*/
@Stable
class DominantColorState(
private val context: Context,
private val defaultColor: Color,
private val defaultOnColor: Color,
cacheSize: Int = 12,
private val isColorValid: (Color) -> Boolean = { true }
) {
var color by mutableStateOf(defaultColor)
private set
var onColor by mutableStateOf(defaultOnColor)
private set
private val cache = when {
cacheSize > 0 -> LruCache<String, DominantColors>(cacheSize)
else -> null
}
suspend fun updateColorsFromImageUrl(url: String) {
val result = calculateDominantColor(url)
color = result?.color ?: defaultColor
onColor = result?.onColor ?: defaultOnColor
}
private suspend fun calculateDominantColor(url: String): DominantColors? {
val cached = cache?.get(url)
if (cached != null) {
// If we already have the result cached, return early now...
return cached
}
// Otherwise we calculate the swatches in the image, and return the first valid color
return calculateSwatchesInImage(context, url)
// First we want to sort the list by the color's population
.sortedByDescending { swatch -> swatch.population }
// Then we want to find the first valid color
.firstOrNull { swatch -> isColorValid(Color(swatch.rgb)) }
// If we found a valid swatch, wrap it in a [DominantColors]
?.let { swatch ->
DominantColors(
color = Color(swatch.rgb),
onColor = Color(swatch.bodyTextColor).copy(alpha = 1f)
)
}
// Cache the resulting [DominantColors]
?.also { result -> cache?.put(url, result) }
}
/**
* Reset the color values to [defaultColor].
*/
fun reset() {
color = defaultColor
onColor = defaultColor
}
}
@Immutable
private data class DominantColors(val color: Color, val onColor: Color)
/**
* Fetches the given [imageUrl] with Coil, then uses [Palette] to calculate the dominant color.
*/
private suspend fun calculateSwatchesInImage(
context: Context,
imageUrl: String
): List<Palette.Swatch> {
val request = ImageRequest.Builder(context)
.data(imageUrl)
// We scale the image to cover 128px x 128px (i.e. min dimension == 128px)
.size(128).scale(Scale.FILL)
// Disable hardware bitmaps, since Palette uses Bitmap.getPixels()
.allowHardware(false)
// Set a custom memory cache key to avoid overwriting the displayed image in the cache
.memoryCacheKey("$imageUrl.palette")
.build()
val bitmap = when (val result = context.imageLoader.execute(request)) {
is SuccessResult -> result.drawable.toBitmap()
else -> null
}
return bitmap?.let {
withContext(Dispatchers.Default) {
val palette = Palette.Builder(bitmap)
// Disable any bitmap resizing in Palette. We've already loaded an appropriately
// sized bitmap through Coil
.resizeBitmapArea(0)
// Clear any built-in filters. We want the unfiltered dominant color
.clearFilters()
// We reduce the maximum color count down to 8
.maximumColorCount(8)
.generate()
palette.swatches
}
} ?: emptyList()
}