你好。我想知道,在SwiftUI中,如何遮罩圆角矩形的内容,以使子矩形夹住角。
在我的示例中,我在zstack上有一个白色的圆角矩形和一个粉红色的矩形,我尝试应用剪裁,但是粉红色的矩形不符合角。
我尝试将.mask应用于白色矩形,但是它给期望值带来了不同的结果(有时它不显示粉红色矩形)。
我确实找到了一个示例,您可以在其中设置自己的cornerRadiusRound Specific Corners SwiftUI
但是我想知道是否可能有一种方法可以掩盖粉红色矩形的内部/主体,使其与父级的圆角矩形一致?
跟随我的代码;
var body: some View {
GeometryReader { geometry in
Color.gray
.edgesIgnoringSafeArea(.top)
.overlay(
ZStack (alignment: .topLeading) {
RoundedRectangle(cornerRadius: 16,
style: .continuous)
.foregroundColor(.white)
.shadow(radius: 10)
// Tried using .mask here
Rectangle()
.fill(Color.pink)
.frame(minWidth: 0, maxWidth: .infinity, maxHeight: 150, alignment: .top)
.clipped()
}
.frame(width: 300, height: 450, alignment: .center)
)
}
.edgesIgnoringSafeArea(.all)
}
如果我正确理解了您的目标,这是一个解决方案(已通过Xcode 11.4测试)
ZStack (alignment: .topLeading) {
RoundedRectangle(cornerRadius: 16,
style: .continuous)
.foregroundColor(.white)
.shadow(radius: 10)
// Tried using .mask here
Rectangle()
.fill(Color.pink)
.frame(minWidth: 0, maxWidth: .infinity, maxHeight: 150, alignment: .top)
.clipped()
}
.clipShape(RoundedRectangle(cornerRadius: 16)) // << here !!
.frame(width: 300, height: 450, alignment: .center)
struct ContentView: View {
var body: some View {
GeometryReader { geometry in
Color.gray
.edgesIgnoringSafeArea(.top)
.overlay(
ZStack (alignment: .topLeading) {
RoundedRectangle(cornerRadius: 16,
style: .continuous)
.foregroundColor(.white)
.shadow(radius: 10)
// Tried using .mask here
Rectangle()
.fill(Color.pink)
.frame(minWidth: 0, maxWidth: .infinity, maxHeight: 150, alignment: .top)
.clipShape(RoundedRectangle(cornerRadius: 16))
}
.frame(width: 300, height: 450, alignment: .center)
)
}
.edgesIgnoringSafeArea(.all)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}