SwiftUI 混合顏色的 mix(with:by:in:) — iOS 18 新功能

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)

完全沒有紅色,得到原本的綠色。

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com