如何在已创建的SwiftUI自定义Shape路径上叠加可交互自定义形状
实现方案
核心思路
不需要修改原有ProgressPath的实现,采用分层渲染的通用方案即可实现需求:底层渲染原有自定义路径,上层叠加可交互节点,节点坐标直接从路径中提取即可。
具体实现
1. 扩展路径取点能力
针对自定义的ProgressPath
可以直接复用原有逻辑暴露顶点坐标,性能最优:
extension ProgressPath { func getAllAnchorPoints(in rect: CGRect) -> [CGPoint] { sectionsByItems.map { point(indexPath: $0, rect: rect) } } }
通用适配任意Shape
如果是未知实现的任意自定义路径,可通过遍历CGPath的方式拿到所有点:
extension Shape { func getAllPathPoints(in rect: CGRect) -> [CGPoint] { var points: [CGPoint] = [] let cgPath = path(in: rect).cgPath cgPath.apply(info: &points) { info, element in guard let pointsPtr = info?.assumingMemoryBound(to: [CGPoint].self) else { return } let pathElement = element.pointee switch pathElement.type { case .moveToPoint, .addLineToPoint: pointsPtr.pointee.append(pathElement.points[0]) case .addQuadCurveToPoint: pointsPtr.pointee.append(pathElement.points[1]) case .addCurveToPoint: pointsPtr.pointee.append(pathElement.points[2]) case .closeSubpath: break @unknown default: break } } return points } }
2. 分层渲染实现可交互节点
使用ZStack分层绘制,节点直接绑定点击交互即可:
struct InteractiveProgressView: View { // 控制路径进度,对应原有numberOfPoints参数 let pointCount: Int // 节点点击回调 let onNodeClick: (Int, CGPoint) -> Void var body: some View { GeometryReader { proxy in let renderRect = proxy.frame(in: .local) let progressPath = ProgressPath(numberOfPoints: pointCount) let anchorPoints = progressPath.getAllAnchorPoints(in: renderRect) ZStack(alignment: .topLeading) { // 底层:原有路径渲染 progressPath .stroke(Color(UIColor.systemBlue), lineWidth: 3) // 上层:可交互节点 ForEach(0..<anchorPoints.count, id: \.self) { index in Circle() .fill(.white) .frame(width: 28, height: 28) .shadow(color: .black.opacity(0.15), radius: 3, x: 0, y: 1) .overlay( Circle() .stroke(Color(UIColor.systemBlue), lineWidth: 2) ) .position(anchorPoints[index]) .onTapGesture { onNodeClick(index, anchorPoints[index]) } } } } .padding(.horizontal, 20) } }
扩展能力:任意路径等距分布节点
如果需要在路径的非顶点位置也生成节点,比如曲线路径上的等距节点,可以通过Path裁切的方式获取任意百分比位置的坐标,完全不依赖Shape的内部实现:
extension Path { /// 获取路径上指定百分比位置的坐标,percent取值范围0~1 func point(at percent: CGFloat) -> CGPoint? { let validPercent = max(0, min(1, percent)) return trimmedPath(from: 0, to: validPercent).currentPoint } }
使用该方法可以在任意形状的路径上生成任意数量的等距可交互节点,满足通用需求。
内容的提问来源于stack exchange,提问作者Vlad Z.
相关产品推荐
相关产品推荐

