将渐变应用于SwiftUI形状中的UIBezierPath

将渐变应用于SwiftUI形状中的UIBezierPath,swift,swiftui,Swift,Swiftui,我正在努力实现以下目标: 结构多段路径:形状{ func pathin rect:CGRect->Path{ 设path1=UIBezierPath //将渐变应用于路径1 设path2=UIBezierPath //将渐变应用于路径2 返回路径Path1.appendpath2.cgPath } } 现在我想我可以用路径包装每个片段,但这会返回一些视图,这意味着我不能将这两个片段附加在一起 直接向UIBezierPath应用渐变需要访问上下文,而不是通过pathCGRect->Path方法传入

我正在努力实现以下目标:

结构多段路径:形状{ func pathin rect:CGRect->Path{ 设path1=UIBezierPath //将渐变应用于路径1 设path2=UIBezierPath //将渐变应用于路径2 返回路径Path1.appendpath2.cgPath } } 现在我想我可以用路径包装每个片段,但这会返回一些视图,这意味着我不能将这两个片段附加在一起

直接向UIBezierPath应用渐变需要访问上下文,而不是通过pathCGRect->Path方法传入

最后,在同一形状内创建两条路径的原因是,我需要缩放它们,同时保持它们彼此的偏移

UIBezierPathUIKIt和PathSwiftUI是不同的东西。。。要创建路径,必须使用它自己的工具。接下来,填充操作w/gradient或任何内容都是绘图时间操作,而不是路径/形状创建的一部分

下面是一些组合到由渐变填充的形状的示例。使用Xcode 11.4进行测试


View.overlay-太棒了!还更新了代码,因此将UIKit与SwiftUI结合使用的想法很清楚。实际上,我想知道这是否与将ZStack与GeometryReader结合使用的效果相同。
struct DemoShape1: Shape {
    func path(in rect: CGRect) -> Path {
        return Path { path in
            path.addRect(rect)
        }
    }
}

struct DemoShape2: Shape {
    func path(in rect: CGRect) -> Path {
        return Path { path in
            path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: rect.size.height/2, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 360), clockwise: true)
        }
    }
}

struct DemoCombinedShape: View {
    var gradient1 = LinearGradient(gradient: Gradient(colors:[.blue, .yellow]), startPoint: .top, endPoint: .bottom)
    var gradient2 = LinearGradient(gradient: Gradient(colors:[.red, .black]), startPoint: .leading, endPoint: .trailing)

    var body: some View {
        // both shapes are rendered in same coordinate space
        DemoShape1().fill(gradient1)
            .overlay(DemoShape2().fill(gradient2))
    }
}

struct TestCombinedShape_Previews: PreviewProvider {
    static var previews: some View {
        DemoCombinedShape()
            .frame(width: 400, height: 300)
    }
}