Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

ios - Drawing with CGPath to SVG output

I made an paint (drawing screen) with CGPath and CAShapeLayer and now my client want the output image scalable and i found SVG Kit SVG Kit but i don't know how to use this library. I didn't find and example neither in the library examples ! Does anyone know how to use this library for converting CGPath to SVG or can give me an tutorial for ?

Thanks in advance !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could start with looking at this file on GitHub. It has a routine to convert a CGPathRef to the d attribute of an SVG Path. I wrote it.

The class method's signature is +(NSString*) svgPathFromCGPath:(CGPathRef)aPath; [Update: Added code snippet below]

#import "SVGPathGenerator.h"

...

CGMutablePathRef pathToBuild = CGPathCreateMutable();
CGPathMoveToPoint(pathToBuild, nil, 10, 10);
CGPathAddQuadCurveToPoint(pathToBuild, nil, 20, 0, 30, 40);
CGPathAddCurveToPoint(pathToBuild, nil, 20, 40, 40, 30, 100, 90);
CGPathAddLineToPoint(pathToBuild, nil, 50, 100);

NSString* aDAttribute =  [SVGPathGenerator svgPathFromCGPath:pathToBuild];
NSLog(@"%@",aDAttribute);

Outputs: M10.0 10.0Q20.0 0.0 30.0 40.0C20.0 40.0 40.0 30.0 100.0 90.0L50.0 100.0

Note, the output will not have a close correspondence if you add arcs, as arcs in SVG and arcs in Quartz are described quite differently.

If you want to output it to a simple SVG file, well then you could do something like:

 CGRect boundingBox = CGPathGetPathBoundingBox(pathToBuild);

NSString* svgAsString = [NSString stringWithFormat:@" <?xml version="1.0" encoding="UTF-8"?> 
                         <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> 
                         <svg  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewport-fill="none" viewBox="%lf, %lf, %lf, %lf" version="1.1" height="%lf" width="%lf" > 
                         <path fill="none" stroke="green" d="%@" /> 
                         </svg>",
                         boundingBox.origin.x, boundingBox.origin.y, boundingBox.size.width, boundingBox.size.height, boundingBox.size.height, boundingBox.size.width, aDAttribute
                         ];

NSData* utf8Data = [svgAsString dataUsingEncoding:NSUTF8StringEncoding];
[utf8Data writeToFile:pathToFile atomically:YES];

(I have not compiled this code).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...