Last active
July 19, 2023 14:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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