将渐变应用于 SwiftUI Shape 中的 UIBezierPath [英] Applying gradient to UIBezierPath in SwiftUI Shape

查看:29
本文介绍了将渐变应用于 SwiftUI Shape 中的 UIBezierPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to accomplish the following:

struct MultiSegmentPaths: Shape {
  func path(in rect: CGRect) -> Path {
    let path1 = UIBezierPath()
    // apply gradient to path 1
    let path2 = UIBezierPath()
    // apply gradient to path 2

    return Path(path1.append(path2).cgPath)
  }
}

现在我想我可以用 Path 包装每个段,但是返回 some View 这意味着我不能将两者附加在一起.

Now I thought I could wrap each segment with Path, but that returns some View which means I can't append the two together.

直接将渐变应用到 UIBezierPath 需要访问上下文 - 这不是通过 path(CGRect) ->路径方法.

And applying a gradient directly to UIBezierPath requires having access to context - which isn't passed in via the path(CGRect) -> Path method.

最后,在同一个 Shape 中创建两条路径的原因是我需要缩放它们,同时保持它们彼此的偏移量.

Finally the reason for creating the two paths within the same Shape is because I need to scale them while maintaining their offsets to each other.

推荐答案

UIBezierPath(UIKIt) 和 Path(SwiftUI) 是不同的东西...创建 Path 你必须使用它自己的工具.接下来,填充操作(带渐变或任何东西)是绘制时间操作,而不是路径/形状创建的一部分.

The UIBezierPath(UIKIt) and Path(SwiftUI) are different things... To create Path you have to use its own instruments. Next, the fill operation (w/ gradient or anything) is drawing time operation, not part of path/shape creation.

以下是一些组合到由渐变填充的形状的示例.使用 Xcode 11.4 测试.

Here is some example of combining to shapes filled by gradients. Tested with Xcode 11.4.

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)
    }
}

这篇关于将渐变应用于 SwiftUI Shape 中的 UIBezierPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆