SwiftUI 混合顏色的 mix(with:by:in:) — iOS 18 新功能
Published in
Jun 20, 2024
SwiftUI Color 在 iOS 18 推出了混色功能 mix(with:by:in:),我們可以方便地混合兩個顏色並設定混合的比例。
以下我們以紅配綠的例子說明混色的效果。
import SwiftUI
struct ContentView: View {
var body: some View {
let redColor = Color(red: 1, green: 0, blue: 0)
let greenColor = Color(red: 0, green: 1, blue: 0)
VStack {
redColor.mix(with: greenColor, by: 0)
redColor.mix(with: greenColor, by: 0.25)
redColor.mix(with: greenColor, by: 0.5)
redColor.mix(with: greenColor, by: 0.75)
redColor.mix(with: greenColor, by: 1)
}
}
}
我們結合紅色跟綠色,利用參數 in 控制混合的比例,in 的數字指的是第二個顏色的比例。
- redColor.mix(with: greenColor, by: 0)
完全沒有綠色,得到原本的紅色。
- redColor.mix(with: greenColor, by: 0.25)
綠色佔 0.25,紅色佔 0.75,得到偏紅的橙紅色。
- redColor.mix(with: greenColor, by: 0.5)
紅綠各佔一半,得到黃褐色。
- redColor.mix(with: greenColor, by: 0.75)
綠色佔 0.75,紅色佔 0.25,得到偏綠的橄欖綠。
- redColor.mix(with: greenColor, by: 1)
完全沒有紅色,得到原本的綠色。