圆形 LinearGradient 上的 ContextMenu 在 SwiftUI 中产生锐边

Ric*_*son 13 gradient contextmenu view swift swiftui

我有以下观点:

struct ContentView: View {
    var body: some View {
        LinearGradient(gradient: Gradient(colors: [.blue, .red]), startPoint: .topTrailing, endPoint: .bottomLeading)
            .cornerRadius(16)
            .frame(width: 140, height: 140)
            .contextMenu {
                Button("", action: {})
            }
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,当 ContextMenu 被调用时,边缘不会被倒圆:

在此处输入图片说明

我尝试了几件事,例如:

  • 应用clipShape修改器将其剪辑到RoundedRectangle
  • 将渐变包装为 RoundedRectangle 视图的背景
  • 使用 Color 而不是 LinearGradient (按预期工作,但不是我需要的)

然而没有工作。任何建议将不胜感激,谢谢!

Ree*_*eed 26

在之后添加以下代码.frame(...)

.contentShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
Run Code Online (Sandbox Code Playgroud)


ZGs*_*ski 12

更新为Swift 5.7.2

总而言之:

// Use the method that takes in ContentShapeKinds
.contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: 30))
Run Code Online (Sandbox Code Playgroud)

放置在 之前 .frame(...)之后 .contextMenu { ... }


详细示例:

var body: some View {
        VStack(alignment: .leading, spacing: .zero) {
            Text("Hello")
                .foregroundColor(.white)
                .font(.title)
        }
        .frame(maxWidth: .infinity, minHeight: 120)
        // These corner radii should match
        .background(RoundedRectangle(cornerRadius: 30).foregroundColor(.blue))
        .contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: 30))
        .contextMenu {
            Button("Look!") { print("We did it!") }
        }
    }
Run Code Online (Sandbox Code Playgroud)

上面的代码生成的结果contextMenu如下所示:

...而不是这个: