使用CGPath绘制到SVG输出 [英] Drawing with CGPath to SVG output
问题描述
我使用CGPath和CAShapeLayer绘制了一个绘图(绘图屏幕),现在我的客户希望输出图像可扩展,我发现SVG Kit SVG工具包但我不知道如何使用此库。我没有在图书馆的例子中找到和示例!有谁知道如何使用这个库将CGPath转换为SVG或者可以给我一个教程?
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 ?
提前致谢!
推荐答案
你可以先看看在GitHub上的这个文件。它有一个例程将CGPathRef转换为SVG路径的d属性。我写了它。
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.
类方法的签名是+(NSString *)svgPathFromCGPath:(CGPathRef)aPath;
[更新:在下面添加了代码段]
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);
产出:
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
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
注意,如果添加弧,输出将没有紧密的对应关系,因为SVG中的弧和Quartz中的弧的描述完全不同。
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.
如果你想将它输出到一个简单的SVG文件,那么你可以这样做:
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).
这篇关于使用CGPath绘制到SVG输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!