カラーピッカーの
スポイドで
色を確認してたけど、
なんか、あやしい。
なんで背景色が違うんや!
【SwiftUI】Default background Color in built-in View Componenthttps://t.co/oZqHxRGiCZ#SwiftUI #プログラミング
— chanzmao (@maochanz) May 16, 2024
数値化してスッキリしたい。
Color から赤、緑、青の値を読み取る
struct ContentView: View {
@Environment(\.self) var environment
@State private var color = Color.red
@State private var resolvedColor: Color.Resolved?
var body: some View {
VStack {
ColorPicker("Select your favorite color", selection: $color)
if let resolvedColor {
Text("Red: \(resolvedColor.red)")
Text("Green: \(resolvedColor.green)")
Text("Blue: \(resolvedColor.blue)")
Text("Opacity: \(resolvedColor.opacity)")
}
}
.padding()
.onChange(of: color, initial: true, getColor)
}
func getColor() {
resolvedColor = color.resolve(in: environment)
}
}
How to read the red, green, and blue values from a Color - a free SwiftUI by Example tutorial
ビルトインの ColorPicker で取得した色を数字化して表示していますね。
分かりやすい !
小数点以下3桁に丸める
ついでに、
小数点以下4桁目を丸めて3桁にして、
0で埋める。
String(format:"%.3f", (0.123456 * 1000).rounded() / 1000)
// 0.123
てか、String のみで四捨五入できる、とか!
Rounding a double value to x number of decimal places in swift - Stack Overflow
まとめ
これらをまとめて整理しておきます。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct TestColorValues: View { | |
var color: Color | |
@Environment(\.self) private var environment | |
private var resolved: Color.Resolved { | |
color.resolve(in: environment) | |
} | |
var body: some View { | |
VStack { | |
Text("\(resolved)") | |
Text(String(format: "R: %.3f", resolved.red)) | |
Text(String(format: "G: %.3f", resolved.green)) | |
Text(String(format: "B: %.3f", resolved.blue)) | |
Text(String(format: "O: %.3f", resolved.opacity)) | |
} | |
.monospaced() | |
.padding() | |
.background(color) | |
} | |
} | |
#Preview("TestColorValues") { | |
VStack { | |
TestColorValues(color: Color(.secondarySystemBackground)) | |
.environment(\.colorScheme, .light) | |
TestColorValues(color: Color(.secondarySystemBackground)) | |
.environment(\.colorScheme, .dark) | |
} | |
} |
Light / Dark 共、
数字が同じになりました。
なるほど、
Dynamic System Color というのは、
environment を見ながら色を変化させているのか !
変化させていたのだ !
便利なのあるわ。
【Swift】よく使いそうな String の format https://t.co/UQ8ITeaSzb #Swift #プログラミング— chanzmao (@maochanz) May 21, 2024