Skip to content

Instantly share code, notes, and snippets.

@gbarcena
Created October 25, 2018 18:27
Show Gist options
  • Save gbarcena/18a6bcd56421b3f88ff81ff86736a691 to your computer and use it in GitHub Desktop.
Save gbarcena/18a6bcd56421b3f88ff81ff86736a691 to your computer and use it in GitHub Desktop.
Get SVG from UIBezierPath
// Converted from: https://github.com/GenerallyHelpfulSoftware/SVGgh/blob/master/SVGgh/SVGRenderer/SVGPathGenerator.m#L1873
extension UIBezierPath {
var svgPathString: String {
var finalString = ""
let cgPath = self.cgPath
var currentPoint = CGPoint.zero
cgPath.applyWithBlock { (aPathElement) in
switch aPathElement.pointee.type {
case .moveToPoint:
currentPoint = aPathElement.pointee.points[0]
finalString = finalString.appendingFormat("M%.1lf,%.1lf", currentPoint.x, currentPoint.y)
case .addLineToPoint:
let newPoint = aPathElement.pointee.points[0]
if newPoint.x == currentPoint.x {
finalString = finalString.appendingFormat("V%.1lf", newPoint.y)
} else if newPoint.y == currentPoint.y {
finalString = finalString.appendingFormat("H%.1lf", newPoint.x)
} else {
finalString = finalString.appendingFormat("L%.1lf,%.1lf", newPoint.x, newPoint.y)
}
currentPoint = newPoint
case .addQuadCurveToPoint:
let controlPoint = aPathElement.pointee.points[0]
let newPoint = aPathElement.pointee.points[1]
finalString = finalString.appendingFormat("Q%.1lf,%.1lf,%.1lf,%.1lf", controlPoint.x, controlPoint.y, newPoint.x, newPoint.y)
currentPoint = newPoint
case .addCurveToPoint:
let controlPoint1 = aPathElement.pointee.points[0]
let controlPoint2 = aPathElement.pointee.points[1]
let newPoint = aPathElement.pointee.points[2]
// swiftlint:disable multiline_arguments
finalString = finalString.appendingFormat("C%.1lf,%.1lf,%.1lf,%.1lf,%.1lf,%.1lf",
controlPoint1.x, controlPoint1.y,
controlPoint2.x, controlPoint2.y,
newPoint.x, newPoint.y)
// swiftlint:enable multiline_arguments
currentPoint = newPoint
case .closeSubpath:
finalString.append("Z")
}
}
return finalString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment