From 9110746078eb926fff6fc89c525d3ffcb48c859d Mon Sep 17 00:00:00 2001 From: Peter Easdown Date: Thu, 19 Mar 2026 07:54:19 +1100 Subject: [PATCH] Added new function to compute the centre point of a path. --- Sources/VectorExtor/CGPath+Extensions.swift | 45 +++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Sources/VectorExtor/CGPath+Extensions.swift b/Sources/VectorExtor/CGPath+Extensions.swift index c057a01..5aabc1f 100644 --- a/Sources/VectorExtor/CGPath+Extensions.swift +++ b/Sources/VectorExtor/CGPath+Extensions.swift @@ -92,6 +92,51 @@ public extension CGPath { return nil } + + + /// This function computes the center point of the path. This swift implementation was taken from + /// https://stackoverflow.com/a/53319889/880807 + /// + /// - Returns: A CGPoint representing the centre point of the path. + func findCenter() -> CGPoint { + class Context { + var sumX: CGFloat = 0 + var sumY: CGFloat = 0 + var points = 0 + } + + let context = Context() + + applyWithBlock { element in + switch element.pointee.type { + case .moveToPoint, .addLineToPoint: + let point = element.pointee.points[0] + context.sumX += point.x + context.sumY += point.y + context.points += 1 + case .addQuadCurveToPoint: + let controlPoint = element.pointee.points[0] + let point = element.pointee.points[1] + context.sumX += point.x + controlPoint.x + context.sumY += point.y + controlPoint.y + context.points += 2 + case .addCurveToPoint: + let controlPoint1 = element.pointee.points[0] + let controlPoint2 = element.pointee.points[1] + let point = element.pointee.points[2] + context.sumX += point.x + controlPoint1.x + controlPoint2.x + context.sumY += point.y + controlPoint1.y + controlPoint2.y + context.points += 3 + case .closeSubpath: + break + @unknown default: + break + } + } + + return CGPoint(x: context.sumX / CGFloat(context.points), + y: context.sumY / CGFloat(context.points)) + } } #endif