Color型をBundleに保存できるようにするカスタムSaver
|
1 2 3 4 5 6 7 8 9 10 |
val ColorSaver = Saver<Color, Int>( save = { it.toArgb() }, // 保存時にInt型(ARGB)に変換 restore = { Color(it) } // 復元時にInt型からColor型を再生成 ) // Compose内で var 変数名 by rememberSaveable(stateSaver = ColorSaver) { mutableStateOf(Color.Red) } |
Color → String
Compose の Color は内部的に Long 値を持っています。
|
1 2 3 4 5 |
import androidx.compose.ui.graphics.Color fun Color.toHexString(): String { return String.format("#%08X", this.value.toULong().toLong()) } |
ただし Compose の内部表現はバージョンによって扱いが少し特殊なので、実務では ARGB を明示的に取り出す方がおすすめです。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import androidx.compose.ui.graphics.Color import androidx.core.graphics.toColorInt fun Color.toHexString(): String { val a = (alpha * 255).toInt() val r = (red * 255).toInt() val g = (green * 255).toInt() val b = (blue * 255).toInt() return String.format( "#%02X%02X%02X%02X", a, r, g, b ) } |
例
val color = Color(0xFF2196F3)
println(color.toHexString())
結果
#FF2196F3
String → Color
|
1 2 3 4 5 6 |
import androidx.compose.ui.graphics.Color import androidx.core.graphics.toColorInt fun String.toComposeColor(): Color { return Color(this.toColorInt()) } |
使用例
val color = "#FF2196F3".toComposeColor()
JSON保存用のデータクラス
@Serializable
data class SettingData(
val buttonColor: String
)
保存
val data = SettingData(
buttonColor = selectedColor.toHexString()
)
JSON
{
"buttonColor": "#FF2196F3"
}
復元
val color = data.buttonColor.toComposeColor()