使用遮罩时出现奇怪的阴影错误

问题描述 投票:0回答:1

您知道如何摆脱这种奇怪的影子行为吗?阴影应not显示圆的线。圆线应仅在矩形内]

var body: some View {
    VStack {
        ZStack {
            Rectangle()
                .fill(Color.yellow)
                .cornerRadius(25)
                .frame(width: 300, height: 700)
                .padding(.leading, 30)
                .padding(.trailing, 30)
                .shadow(color: .gray, radius: 12, x: 0, y: 4)

            Rectangle()
                .fill(Color.white)
                .opacity(0.2)
                .cornerRadius(25)
                .frame(width: 1300, height: 1300)
                .mask (
                    Circle()
                        .fill(Color.backgroundColor)
                        .offset(x: 80, y: -900)
            )
        }
    }
}

enter image description here

swift xcode swiftui mask
1个回答
2
投票

起初,让您的视图更“通用”

struct MyView: View {
    let relativeRadius: CGFloat
    let unitPoint: UnitPoint
    let color: Color
    let cornerRadius: CGFloat
    let shadowRadius: CGFloat
    var body: some View {
        GeometryReader { proxyOuter in
            Rectangle().fill(self.color)
        .overlay(
            GeometryReader { proxy in
            Circle()
                .fill(Color.primary.opacity(0.2))
                .colorInvert().offset(x: proxy.size.width * self.unitPoint.x, y: -proxy.size.height * self.unitPoint.y)
                .frame(width: proxy.size.width * self.relativeRadius, height: proxy.size.height * self.relativeRadius)
            }
        )
            .frame(width: proxyOuter.size.width, height: proxyOuter.size.height)
            // mask is redundant if using .cornerRadius, which is "mask" as well 
            .mask(Color.primary)
                .cornerRadius(self.cornerRadius)
                // see more parameters for shadow
                // i like :-)
                // .shadow(color: Color.secondary, radius: self.shadowRadius, x: self.shadowRadius, y: self.shadowRadius)
                .shadow(radius: self.shadowRadius)
        }
    }
}

然后以“标准方式”使用它]

struct ContentView: View {
    var body: some View {
        MyView(relativeRadius: 1.5, unitPoint: UnitPoint(x: 0.2, y: 0.75), color: Color.yellow, cornerRadius: 30, shadowRadius: 10)
            .frame(width: 300, height: 300, alignment: .center)
            // to see the bounding box (used for stacking), uncomment next line
            //.border(Color.red)
    }
}

在这里您可以看到结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.