SVG在iOS中使用总结

SVG简介

SVG是一种用XML定义的语言,用来描述二维矢量及矢量/栅格图形。SVG提供了3种类型的图形对象:矢量图形(vectorgraphicshape例如:由直线和曲线组成的路径)、图象(image)、文本(text)。图形对象还可进行分组、添加样式、变换、组合等操作,特征集包括嵌套变换(nestedtransformations)、剪切路径(clippingpaths)、alpha蒙板(alphamasks)、滤镜效果(filtereffects)、模板对象(templateobjects)和其它扩展(extensibility)。SVG图形是可交互的和动态的,可以在SVG文件中嵌入动画元素或通过脚本来定义动画。

SVG优势

  1. SVG 可被非常多的工具读取和修改(比如记事本)
  2. SVG 与 JPEG 和 GIF 图像比起来,尺寸更小,且可压缩性更强。
  3. SVG 是可伸缩的
  4. SVG 图像可在任何的分辨率下被高质量地打印
  5. SVG 可在图像质量不下降的情况下被放大
  6. SVG 图像中的文本是可选的,同时也是可搜索的(很适合制作地图)
  7. SVG 可以与 JavaScript 技术一起运行
  8. SVG 是开放的标准
  9. SVG 文件是纯粹的 XML

SVG在iOS中的运用

SVG在iOS中可以用UIWebView来加载:

    NSString *svgName = @"fruit_map.svg";
    NSString *svgPath = [[NSBundle mainBundle] pathForResource:svgName ofType:nil];
    NSData *svgData = [NSData dataWithContentsOfFile:svgPath];
    NSString *reasourcePath = [[NSBundle mainBundle] resourcePath];
    NSURL *baseUrl = [[NSURL alloc] initFileURLWithPath:reasourcePath isDirectory:true];
    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = CGRectMake(0, CGRectGetMaxY(htpBtn.frame)+50, self.view.bounds.size.width, 300);
    [webView loadData:svgData MIMEType:@"image/svg+xml" textEncodingName:@"UTF-8" baseURL:baseUrl];
    [self.view addSubview:webView];

这种方法来加载SVG,虽然也可以,但是却存在诸如放大缩小、点击交互等问题。所以一般更加推荐使用SVGKit

SVGKit使用

1、SVG创建

    SVGKImage *svgImage = [SVGKImage imageNamed:svgName];
    SVGKFastImageView *svgView = [[SVGKFastImageView alloc] initWithSVGKImage:svgImage];
    svgView.frame = CGRectMake(0, CGRectGetMaxY(htpBtn.frame)+50, self.view.bounds.size.width, 300);
    [self.view addSubview:svgView];

2、实现SVG放大缩小功能

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIScrollView *scrollViewForSVG = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, self.view.bounds.size.height-200)];
    scrollViewForSVG.delegate = self;
    [self.view addSubview:scrollViewForSVG];
    _scrollViewForSVG = scrollViewForSVG;

    SVGKFastImageView *contentView = [[SVGKFastImageView alloc] initWithFrame:scrollViewForSVG.frame];
    [scrollViewForSVG addSubview:contentView];
    self.contentView = contentView;
    SampleFileInfo *info = [SampleFileInfo sampleFileInfoWithFilename:@"12.svg"];
    [self loadSVGFrom:info.source];
}

-(void)loadSVGFrom:(SVGKSource *) svgSource{
    [SVGKImage imageWithSource:svgSource
                  onCompletion:^(SVGKImage *loadedImage, SVGKParseResult* parseResult)
     {
         dispatch_async(dispatch_get_main_queue(), ^{
             loadedImage.DOMDocument.title = @"123";
             [self internalLoadedResource:svgSource parserOutput:parseResult createImageViewFromDocument:loadedImage];
         });
     }];
}

-(void) internalLoadedResource:(SVGKSource*) source parserOutput:(SVGKParseResult*) parseResult createImageViewFromDocument:(SVGKImage*) document
{
    SVGKImageView* newContentView = nil;
    newContentView = [[SVGKFastImageView alloc] initWithSVGKImage:document];
    ((SVGKFastImageView*)newContentView).disableAutoRedrawAtHighestResolution = TRUE;
    [self didLoadNewResourceCreatingImageView:newContentView];
}

-(void)didLoadNewResourceCreatingImageView:(SVGKImageView*) newContentView{
    if (newContentView != nil) {
        self.contentView = newContentView;
        self.contentView.showBorder = YES;
        [self.scrollViewForSVG addSubview:self.contentView];

        [self.scrollViewForSVG setContentSize: self.contentView.frame.size];
        float screenToDocumentSizeRatio = self.scrollViewForSVG.frame.size.width / self.contentView.frame.size.width;
        self.scrollViewForSVG.minimumZoomScale = MIN( 2.5, screenToDocumentSizeRatio );
        self.scrollViewForSVG.maximumZoomScale = MAX( 2.5, screenToDocumentSizeRatio );
        [self.scrollViewForSVG setZoomScale:1.00 animated:YES];
    }
}

实现UIScrollView的代理方法:

//代理方法,告诉ScrollView要缩放的是哪个视图
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.contentView;
}
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)finalScale
{
     view.transform = CGAffineTransformIdentity; 
     view.bounds = CGRectApplyAffineTransform(view.bounds, CGAffineTransformMakeScale(finalScale, finalScale));
     [view setNeedsDisplay];

     self.scrollViewForSVG.minimumZoomScale /= finalScale;
     self.scrollViewForSVG.maximumZoomScale /= finalScale;
}

3、SVG上进行路线规划

SVG上的线路规划,需要从服务器中拿取相关的坐标点,然后将其绘制在SVG上。具体实现如下:

-(void) didLoadNewResourceCreatingImageView:(SVGKImageView*) newContentView
{
    if( newContentView != nil )
    {
        self.contentView = newContentView;
        self.contentView.showBorder = YES;

        /** Move the gesture recognizer onto the new one */
        if( self.tapGestureRecognizer == nil )
        {
            self.tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
        }
        [self.contentView addGestureRecognizer:self.tapGestureRecognizer];
       [self.contentView addSubview:self.imageView];
        [self.scrollViewForSVG addSubview:self.contentView];

        [self.scrollViewForSVG setContentSize: self.contentView.frame.size];
        float screenToDocumentSizeRatio = self.scrollViewForSVG.frame.size.width / self.contentView.frame.size.width;
        self.scrollViewForSVG.minimumZoomScale = MIN( 2.5, screenToDocumentSizeRatio );
        self.scrollViewForSVG.maximumZoomScale = MAX( 2.5, screenToDocumentSizeRatio );
        [self.scrollViewForSVG setZoomScale:1.00 animated:YES];
    }

    UIBezierPath * path = [[UIBezierPath alloc]init];
    path.lineWidth = 1.0;
    [path moveToPoint:CGPointMake( 0, 527 )];
    [path addLineToPoint:CGPointMake( 90, 527 )];
    [path addLineToPoint:CGPointMake( 99.96, 541.85 )];
    [path addLineToPoint:CGPointMake( 153.13, 546.03 )];
    [path addLineToPoint:CGPointMake( 204.96, 560.85 )];
    [path addLineToPoint:CGPointMake( 250.96, 585.85 )];
    [path addLineToPoint:CGPointMake( 310.87, 636.47 )];
    [path addLineToPoint:CGPointMake( 336.96, 662.85 )];
    [path addLineToPoint:CGPointMake( 402.5, 641.5 )];
    [path addLineToPoint:CGPointMake( 485.5, 647.5 )];
    CAShapeLayer *lineChartLayer = [CAShapeLayer layer];
    lineChartLayer.path = path.CGPath;
    lineChartLayer.strokeColor = [UIColor redColor].CGColor;
    lineChartLayer.fillColor = [[UIColor clearColor] CGColor];
    // 默认设置路径宽度为0,使其在起始状态下不显示
    lineChartLayer.lineWidth = 1;
    [self.contentView.layer addSublayer:lineChartLayer];
}

效果如下:


©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,490评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,581评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,830评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,957评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,974评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,754评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,464评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,847评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,995评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,137评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,819评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,482评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,023评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,149评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,409评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,086评论 2 355

推荐阅读更多精彩内容

  • 背景 当 JavaScript 被 Netscape 公司发明出来时,它被用来做一些琐细的事情,比如校验表单、计算...
    locky丶阅读 2,180评论 0 5
  • 阅读原文 SVG矢量动画机制   Google在Android 5.X中增加了对 SVG 矢量图形的支持, 这对于...
    GeekGray阅读 5,859评论 0 4
  • 一、相关概念 1、位图与矢量图概念及对比 位图 :又叫点阵图或像素图,计算机屏幕上的图你是由屏幕上的发光点(即像素...
    sean92_阅读 4,759评论 1 2
  • 今日听了罗胖的《计划的用处》,深有同感。 几乎所有人都知道计划, 几乎所有人都做过计划, 然而有多少人明白计划的意...
    剑心折手阅读 462评论 0 0
  • 1、坏计划好过没计划。无论是创业还是个人成长,大胆尝试永远胜过平庸保守。很多事情,不去尝试你永远无法知道结果会如何...
    Maymei6阅读 147评论 2 2