ios - 如何在 SwiftUI 中为一系列路径的形状绘制边框?

标签 ios swiftui

我在 SwiftUI 中有一个自定义形状,它是一系列形成不同线条的 CGPoints。
我希望能够在每个单独的路径周围绘制边框,现在我唯一能想到的就是创建另一个 Shape,它采用原始 CGPoints 并为每个点添加 x,y 填充,但我想看看是否还有另一个可能是我找不到的内置方式。
例如,我的形状是

      -----
           |
           |
并且我想添加一个边界形状,以便我可以检测何时有人处于边界中,其中 # 代表原始路径周围的新可能形状。
     ######## 
     #----- #
      ######
          #|#
          #|#
           #
有没有办法实现这个内置的?
编辑:我目前正在考虑绘制边界的代码,很早,但给出了我在想的要点
struct DrawShapeBorder: Shape {
    var points: [CGPoint]

    func path(in rect: CGRect) -> Path {
        var path: Path = Path()

        guard let startingPoint = points.first else {
            return path
        }

        // go up
        let upStartingPoint = CGPoint(x: startingPoint.x, y: startingPoint.y + 5)
        path.move(to: upStartingPoint)

        for pointLocation in points {
            
            path.addLine(to: pointLocation)
        }

        return path
    }
}

最佳答案

@Evergreen suggested在评论中,您可以使用 stroke修饰符...但棘手的是你只能应用其中之一,所以你不能做 .stroke().stroke().stroke() ,不像 .shadow().shadow().shadow() .
但是,您可以使用 ZStack 解决此问题。包含形状的 2 个副本,然后为每个副本添加不同的笔划。

struct ContentView: View {
    var body: some View {
        DrawShapeBorder(points: [
            CGPoint(x: 100, y: 150),
            CGPoint(x: 300, y: 100),
            CGPoint(x: 300, y: 200),
            CGPoint(x: 100, y: 200)
        ])
        .stroked()
    }
}
struct DrawShapeBorder: Shape {
    
    /// add the double border
    func stroked() -> some View {
        ZStack {
            self.stroke(Color.red, style: StrokeStyle(lineWidth: 20, lineCap: .round, lineJoin: .round))
            self.stroke(Color.white, style: StrokeStyle(lineWidth: 10, lineCap: .round, lineJoin: .round))
        }
    }
    
    var points: [CGPoint]
    
    func path(in rect: CGRect) -> Path {
        var path: Path = Path()
        
        guard let startingPoint = points.first else {
            return path
        }
        
        // go up
        let upStartingPoint = CGPoint(x: startingPoint.x, y: startingPoint.y + 5)
        path.move(to: upStartingPoint)
        
        for pointLocation in points {
            path.addLine(to: pointLocation)
        }
        
        return path
    }
}
结果:
Path with white border, but extra red border around it

关于ios - 如何在 SwiftUI 中为一系列路径的形状绘制边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67341139/

相关文章:

swiftui - 检测用户是否在 SwiftUI 中点击了屏幕,包括按钮

IOS 8 改变键盘高度

ios - 使用公共(public)/非公共(public)/私有(private) API 在设备上获取顶级 UIWIndow/UIView

python - Pythonista 如何在 App Store 限制下工作?

如果Button具有buttonStyle,则SwiftUI键盘快捷方式将不起作用

ios - SwiftUI 拖动手势因多点触控而卡住

swiftui - 忽略安全区域未覆盖 View 底部

ios - 我可以在 Swift 中以编程方式删除/删除类实例吗

ios - NSOperationQueue 和传递数据

swiftui - 如何正确使用matchedGeometry?