这是我的两个重叠矩形的代码,并对它们应用了不透明度。
var body: some View {
let r = Rectangle()
.foregroundColor(.blue)
.frame(width: 80, height: 40)
.position(x: 60, y: 110)
let r2 = Rectangle()
.foregroundColor(.green)
.frame(width: 80, height: 40)
.position(x: 70, y: 120)
return ZStack {
r
r2
}.opacity(0.5)
}
Run Code Online (Sandbox Code Playgroud)
它们看起来像这样:
它们需要看起来像这样(红色矩形只是为了更好地看到不透明度):
所以我想说的是蓝色矩形在绿色矩形下面不应该是可见的。因为不透明度应该作为一个组应用于它们,而不是一个一个地单独应用于它们中的每一个。我怎样才能做到这一点?
我正在尝试在矩形上渲染线性渐变。这是代码:
Rectangle()
.foregroundColor(Color.red)
.overlay(
LinearGradient(gradient: Gradient(colors: [.red, .yellow, .blue]), startPoint: .topLeading, endPoint: .bottomTrailing)
)
.frame(width: 300, height: 200)
.position(x: 170, y: 120)
Run Code Online (Sandbox Code Playgroud)
当我将其渲染在正方形上时,一切看起来都是正确的:
然而,当我在矩形上渲染它时,它看起来不再像从顶部前角到底部尾随。它看起来就像是被剪辑的同一个:
这是它在 svg 中的渲染方式(蓝色看起来不一样,但这不是重要的部分),以及我希望它在 swift 中的外观:
黄色对角线应该直接从一个角到另一个角,因为我指定了startPoint: .topLeading, endPoint: .bottomTrailing
. 这里说SwiftUI 对角线 LinearGradient 在一个矩形中,这是一个标准行为,没关系 - 我并不是想说 SwiftUI 渲染它不正确,我只是需要一种方法让它看起来像 svg 中的那样。
我正在制作两个渐变:一个在objectBoundingBox单元中,另一个在userSpaceOnUse中。目的是使它们看起来相同。但是它们又有所不同。这是svg文件。
<svg width="500" height="500" viewBox="0 0 500 500" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="user-grad" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="200" y2="100">
<stop stop-color="orange" offset="0"/>
<stop stop-color="blue" offset="1"/>
</linearGradient>
<linearGradient id="box-grad" x1="0" y1="0" x2="1" y2="1">
<stop stop-color="orange" offset="0"/>
<stop stop-color="blue" offset="1"/>
</linearGradient>
</defs>
<rect x="0" y="0" width="200" height="100" fill="url(#user-grad)"/>
<rect x="250" y="0" width="200" height="100" fill="url(#box-grad)"/>
</svg>
Run Code Online (Sandbox Code Playgroud)
这是它的样子
他们不应该看起来一样吗?