Created
August 6, 2022 17:10
-
-
Save Akhu/cc6acd01b974d311ea5e5fa62896c46a to your computer and use it in GitHub Desktop.
Quick tool to convert SVG Path to SwiftUI Path, I did this quickly, it is missing many SVG path identifier but you will figure out how to make it work yourself it's pretty easy.
This file contains hidden or 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
/** | |
* Creating SwiftUI Path from SVG path data | |
*/ | |
const regex = /([MmLlSsQqLlHhVvCcSsQqTtAaZz]){1} ((-?[0-9]*\.?\d+) ){2,6}|Z/mg; | |
//Replace content of svgPath by your SVG Path data | |
const svgPath = `M 13.0286 28 C 22.123 12 26.6701 4.3722 32.6067 1.7291 C 37.7849 -0.5764 43.698 -0.5764 48.8762 1.7291 C 54.8128 4.3722 59.3599 12.2481 68.4543 28 C 77.5486 43.7519 82.0958 51.6278 81.4165 58.0906 C 80.824 63.7277 77.8674 68.8487 73.2818 72.1803 C 68.0245 76 58.9301 76 40.7414 76 C 22.5528 76 13.4584 76 8.2011 72.1803 C 3.6155 68.8487 0.6589 63.7277 0.0664 58.0906 C -0.6129 51.6278 3.9343 43.7519 13.0286 28 Z`; | |
let regexDetectionResult; | |
const data = [] | |
while ((regexDetectionResult = regex.exec(svgPath)) !== null) { | |
// This is necessary to avoid infinite loops with zero-width matches | |
if (regexDetectionResult.index === regex.lastIndex) { | |
regex.lastIndex++; | |
} | |
// The result can be accessed through the `regexDetectionResult`-variable. | |
regexDetectionResult.forEach((match, groupIndex) => { | |
//console.log(`Found match, group ${groupIndex}: ${match}`); | |
}); | |
data.push(regexDetectionResult) | |
} | |
//Swift Code generation | |
let swiftCode = `Path { path in\n` | |
data.forEach(element => { | |
let key = element[1] ?? element[0] | |
let values = element[0].trim().split(" ") | |
switch(key) { | |
case 'C': | |
//console.log('Curve Data', extractCoordinatesFromCurve(values)) | |
let curveObject = extractCoordinatesFromCurve(values) | |
swiftCode += `\tpath.addCurve(to: CGPoint(x: ${curveObject.x}, y: ${curveObject.y}), control1: CGPoint(x: ${curveObject.x1}, y: ${curveObject.y1}), control2: CGPoint(x: ${curveObject.x2}, y: ${curveObject.y2}) )\n` | |
break | |
case 'M': | |
let moveObject = extractCoordinatesFromMove(values) | |
swiftCode += `\tpath.move(to: CGPoint(x: ${moveObject.x}, y: ${moveObject.y}))\n` | |
break | |
case 'Z': | |
swiftCode += `\n}` | |
} | |
}); | |
console.log(swiftCode) | |
/** | |
* Extracting svg path curve data into object | |
*/ | |
function extractCoordinatesFromCurve(curve) { | |
return { | |
x1: curve[1], | |
y1: curve[2], | |
x2: curve[3], | |
y2: curve[4], | |
x: curve[5], | |
y: curve[6] | |
} | |
} | |
function extractCoordinatesFromMove(move){ | |
return { | |
x: move[1], | |
y: move[2] | |
} | |
} } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment