Skip to content

Instantly share code, notes, and snippets.

@dceddia
Last active July 19, 2023 14:51
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dceddia/851f3869fa6f7abe92c142e1478c0ad7 to your computer and use it in GitHub Desktop.
Save dceddia/851f3869fa6f7abe92c142e1478c0ad7 to your computer and use it in GitHub Desktop.
Convert a CGPath to an SVG element with this Swift extension to CGPath
//
// CGPath+svg.swift
//
// Create an SVG element from a CGPath.
//
// Created by Dave Ceddia.
// MIT Licensed
//
// Inspired by: https://github.com/mro/MROGeometry/blob/master/MROGeometry/CGPathWriter.c
import Foundation
import Cocoa
extension CGPath {
func svg(width: CGFloat, height: CGFloat, stroke: String = "black", fill: String = "transparent") -> String {
return """
<svg width="\(width)" height="\(height)" xmlns="http://www.w3.org/2000/svg">
<path d="\(svgPath)" stroke="\(stroke)" fill="\(fill)" />
</svg>
"""
}
var svgPath: String {
var result = ""
applyWithBlock() { element in
let el = element.pointee
switch(el.type) {
case .moveToPoint:
result += String(format: "M%f,%f", el.points[0].x, el.points[0].y)
case .addLineToPoint:
result += String(format: "L%f,%f", el.points[0].x, el.points[0].y)
case .addQuadCurveToPoint:
result += String(format: "Q%f,%f,%f,%f", el.points[0].x, el.points[0].y, el.points[1].x, el.points[1].y)
case .addCurveToPoint:
result += String(format: "C%f,%f,%f,%f,%f,%f", el.points[0].x, el.points[0].y, el.points[1].x, el.points[1].y, el.points[2].x, el.points[2].y)
case .closeSubpath:
result += "Z"
default:
// shouldn't hit this. but if we do, ignore it
break
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment