- Published on
Color创建一个常量灰阶颜色值
- Authors
- Name
Color的init(_:white:opacity:)方法的误解
第一次看到这个方法的时候是我在学习scaledToFit这个方法的时候,apple有一个官方代码是这样的:
Circle()
.fill(Color.pink)
.scaledToFit()
.frame(width: 300, height: 150)
.border(Color(white: 0.75))

我们可以看到在粉色的圆形之外,添加了一个0.75灰阶的矩形边框。这里的外框就是通过代码 .border(Color(white:0.75))来实现的 Color(white:0.75)我一开始以为是创建一个白色的透明度为0.75的颜色,其实不是。这里真正的效果是创建一个 0.75灰阶的颜色,如果white取0就是黑色,取1就是白色。
在Apple中的定义
init(
_ colorSpace: Color.RGBColorSpace = .sRGB,
white: Double,
opacity: Double = 1
)
/// Creates a constant grayscale color.
///
/// This initializer creates a constant color that doesn't change based
/// on context. For example, it doesn't have distinct light and dark
/// appearances, unlike various system-defined colors, or a color that
/// you load from an Asset Catalog with ``init(_:bundle:)``.
///
/// A standard sRGB color space clamps the `white` component
/// to a range of `0` to `1`, but SwiftUI colors
/// use an extended sRGB color space, so
/// you can use component values outside that range. This makes it
/// possible to create colors using the ``RGBColorSpace/sRGB`` or
/// ``RGBColorSpace/sRGBLinear`` color space that make full use of the wider
/// gamut of a diplay that supports ``RGBColorSpace/displayP3``.
///
/// - Parameters:
/// - colorSpace: The profile that specifies how to interpret the color
/// for display. The default is ``RGBColorSpace/sRGB``.
/// - white: A value that indicates how white
/// the color is, with higher values closer to 100% white, and lower
/// values closer to 100% black.
/// - opacity: An optional degree of opacity, given in the range `0` to
/// `1`. A value of `0` means 100% transparency, while a value of `1`
/// means 100% opacity. The default is `1`.
public init(_ colorSpace: Color.RGBColorSpace = .sRGB, white: Double, opacity: Double = 1)