Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions Sources/VectorExtor/CGPath+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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