IOS绘制矢量图 SVGKIT 的使用

来源:互联网 发布:融资租赁软件 编辑:程序博客网 时间:2024/05/29 12:24

之前遇到的需求使用SVG矢量图,那么问题来了拿到SVG数据以后怎么去绘制。 最后找到了SVGKIT 这个第三方库。

下载地址 https://github.com/SVGKit/SVGKit

首先导入就不用说了吧 可以用pod倒入

初始化SVGKIT

我使用的是SVGKFastImageView 这个类创建的对象

- (void) initSVGWithName:(NSString *)path{    //<! 初始化svg    svgFastImageview = [[SVGKFastImageView alloc] initWithSVGKImage:[SVGKImage imageWithContentsOfFile:path]];    //<! 设置svg的frame    svgFastImageview.frame = _SVGView.frame;    //<! 给svg图片添加点击手势    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];    [svgFastImageview addGestureRecognizer:tap];    [_SVGView addSubview:svgFastImageview];}

path 传SVG文件的路径 里面的SVGView是用于承载svgFastImageview的一个View 添加手势是为了识别在svg图上面的点击操作,因为需要点击svg区域获取到相应的信息。

-(void) handleTapGesture:(UITapGestureRecognizer*) recognizer{    //<! 获取当前点击点在svg上的坐标    CGPoint p = [recognizer locationInView:svgFastImageview];    //<! 创建一个图层 去接收CALayerTree    CALayer *hitLayerT ;    if ([svgFastImageview isKindOfClass:[SVGKFastImageView class]]) {        //<! 设置layer        hitLayerT = svgFastImageview.image.CALayerTree;        SVGKImage *svgimage = svgFastImageview.image;        //<! svg点击区域        CGSize scaleConvertImageToViewForHitTest = CGSizeMake( svgFastImageview.bounds.size.width / svgimage.size.width, svgFastImageview.bounds.size.height / svgimage.size.height );        //<! 当前点击点        p = CGPointApplyAffineTransform( p, CGAffineTransformInvert( CGAffineTransformMakeScale( scaleConvertImageToViewForHitTest.width, scaleConvertImageToViewForHitTest.height)) );    }else    {        hitLayerT = svgFastImageview.layer;    }    //<! 获取当前点击图层    CALayer *hitlayer = [hitLayerT hitTest:p];    NSLog(@"%@",hitlayer.actions);}

首先我们可以通过点击 找到点击的图层 但是现在怎么实现传递对应的数据过去呢。 一般来说对应的数据都封装在svg文件当中,所以要找到SVGKIT的中对于解析svg文件的时候标签的时候的代码添加自己想到的。

经过一翻寻找 发现解析在一个叫做SVGElement 的类当中先找到了解析svg的方法,首先我在这个类中添加了一个字典infoDictionary 把想要的标签解析出来的数据存在这个字典当中

  • (void)postProcessAttributesAddingErrorsTo:(SVGKParseResult *)parseResult
    {
    // 先判断id存不存在
    if( [[self getAttribute:@”id”] length] > 0 )
    {
    self.identifier = [self getAttribute:@”id”];
    [self.infoDictionary setObject:[self getAttribute:@”id”] forKey:@”id”];
    }
    }

然后在SVGHleperUtilities 这个类中找到+(void) configureCALayer:(CALayer*) layer usingElement:(SVGElement*) nonStylableElement
这个方法

在下面添加一行代码

layer.actions = nonStylableElement.infoDictionary;

把infoDictionary 复制给layer的Action (这里纯粹是为了图方便,因为layer的acitons 字典这个属性也用不上,所以就干脆用来传值了)。

这个时候 前面的操作手势的方法中输出的 NSLog(@”%@”,hitlayer.actions); 就会携带对应区域的信息了 然后根据键值取出需要的,就可以实现svgkit 获取对于区域的信息了。

因为没怎么写过博客,可能说的不是特别清楚,希望大家勿怪。 有什么不太懂的欢迎留言。

0 0