SwiftUI使用overlay后边缘可见

6

我正在尝试使用overlay在我的一个视图中创建圆角边缘。

.background(Color.gray.opacity(0.2))
.overlay(
    RoundedRectangle(cornerRadius: 10)
        .stroke(Color.gray.opacity(0.2), lineWidth: 1)
)

问题在于我仍然可以看到背景的边缘和描边。如何裁剪边缘?

enter image description here

3个回答

13

即使使用透明度,您的视图也无法通过叠加层进行点击,因此解决方案是使用如下所示的剪辑形状和背景

演示

struct DemoRoundRectView: View {
    var body: some View {
        Text("DEMO")
            .frame(width: 100, height: 50)
            .background(Color.gray.opacity(0.2))
            .clipShape(RoundedRectangle(cornerRadius: 10)) // clip corners
            .background(
                RoundedRectangle(cornerRadius: 10) // stroke border
                    .stroke(Color.gray.opacity(0.2), lineWidth: 1)
            )
    }
}

4
struct ContentView: View {

    var body: some View {
        Rectangle()
            .fill(Color.orange)
            .frame(width: 200, height: 200, alignment: .center)
            .cornerRadius(10)
            .overlay(
                RoundedRectangle(cornerRadius: 10)
                    .stroke(Color.red, lineWidth: 1)
        )
    } }

试试这个。


我无法使用.fill(),因为我的视图不是一个实心的形状。我添加了其余的代码,但问题仍然存在。@uikenan - M1X
1
好的,你应该使用.cornerRadius。但是如果仍然不行,你应该增加代码示例。 - uikenan

1

现在看起来你的修改器大概是这样的:

.cornerRadius(10)
.background(Color.gray.opacity(0.2))
.overlay(
    RoundedRectangle(cornerRadius: 10)
        .stroke(Color.gray.opacity(0.2), lineWidth: 1)
)

相反,您需要更改视图修饰符的顺序,因为顺序很重要!您正在将边角四舍五入然后应用背景,而您应该应用背景,以便圆角半径可以剪辑它。

尝试这个:

.background(Color.gray.opacity(0.2))
.cornerRadius(10)
.overlay(
    RoundedRectangle(cornerRadius: 10)
        .stroke(Color.gray.opacity(0.2), lineWidth: 1)
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接