关于这个问题,我已经在另一篇blog中有所提及:

CoreText精彩文字轮廓绘制动画的一点改进

不过原有的转换代码使用Obj-C写的,在这里我们尝试将其转换为Swift语言,然后利用它实现一个测试小程序.

首先贴出原来Objc的代码:

- (void) setupTextLayer
{
    if (self.pathLayer != nil) {
        [self.penLayer removeFromSuperlayer];
        [self.pathLayer removeFromSuperlayer];
        self.pathLayer = nil;
        self.penLayer = nil;
    }

    // Create path from text
    // See: http://www.codeproject.com/KB/iPhone/Glyph.aspx
    // License: The Code Project Open License (CPOL) 1.02 http://www.codeproject.com/info/cpol10.aspx
    CGMutablePathRef letters = CGPathCreateMutable();

    CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica-Bold"), 72.0f, NULL);
    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
                           (id)font, kCTFontAttributeName,
                           nil];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"你好,大熊猫侯佩!"
    //NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"hello world!"
                                                                     attributes:attrs];
    CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)attrString);
    CFArrayRef runArray = CTLineGetGlyphRuns(line);

    // for each RUN
    for (CFIndex runIndex = 0; runIndex < CFArrayGetCount(runArray); runIndex++)
    {
        // Get FONT for this run
        CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runArray, runIndex);
        CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);

        // for each GLYPH in run
        for (CFIndex runGlyphIndex = 0; runGlyphIndex < CTRunGetGlyphCount(run); runGlyphIndex++)
        {
            // get Glyph & Glyph-data
            CFRange thisGlyphRange = CFRangeMake(runGlyphIndex, 1);
            CGGlyph glyph;
            CGPoint position;
            CTRunGetGlyphs(run, thisGlyphRange, &glyph);
            CTRunGetPositions(run, thisGlyphRange, &position);

            // Get PATH of outline
            {
                CGPathRef letter = CTFontCreatePathForGlyph(runFont, glyph, NULL);
                CGAffineTransform t = CGAffineTransformMakeTranslation(position.x, position.y);
                CGPathAddPath(letters, &t, letter);
                CGPathRelease(letter);
            }
        }
    }
    CFRelease(line);

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointZero];
    [path appendPath:[UIBezierPath bezierPathWithCGPath:letters]];

    CGPathRelease(letters);
    CFRelease(font);

    CAShapeLayer *pathLayer = [CAShapeLayer layer];
    pathLayer.frame = self.animationLayer.bounds;
    pathLayer.bounds = CGPathGetBoundingBox(path.CGPath);
    //pathLayer.backgroundColor = [[UIColor yellowColor] CGColor];
    pathLayer.geometryFlipped = YES;
    pathLayer.path = path.CGPath;
    pathLayer.strokeColor = [[UIColor blackColor] CGColor];
    pathLayer.fillColor = nil;
    pathLayer.lineWidth = 5.0f;
    //pathLayer.lineJoin = kCALineJoinBevel;
    pathLayer.lineJoin = kCALineJoinMiter;

    [self.animationLayer addSublayer:pathLayer];

    self.pathLayer = pathLayer;

    //happy commit
    NSLog(@"hello world!!!");

    //UIImage *penImage = [UIImage imageNamed:@"noun_project_347_2.png"];
    UIImage *penImage = [UIImage imageNamed:@"bee.png"];
    CALayer *penLayer = [CALayer layer];
    penLayer.contents = (id)penImage.CGImage;
    penLayer.anchorPoint = CGPointZero;
    penLayer.frame = CGRectMake(0.0f, 0.0f, penImage.size.width/5, penImage.size.height/5);
    [pathLayer addSublayer:penLayer];

    self.penLayer = penLayer;
}

看起来颇长啊!不过不要太在意,因为我们要用Swift重写的代码只提取其中中间的一部分,这样可以更好的重用.

新建一个项目,基于Swift语言.

在项目中新建一个Swift源代码文件,该文件扩展了String类,我们在其扩展中先写一个帮助方法的存根:

extension String{
    func toPath(font:CTFont)->CGPath{

    }
}

toPath方法用来实现任意String实例到CGPath路径的转换,在其中添加如下内容:

let letters:CGMutablePathRef = CGPathCreateMutable()
        let attrs = [kCTFontAttributeName as String:font]
        let attrString:NSAttributedString = NSAttributedString(string: self, attributes: attrs)

        let line:CTLine = CTLineCreateWithAttributedString(attrString)
        let runArray = CTLineGetGlyphRuns(line)

        for runIndex in 0..<CFArrayGetCount(runArray){
            let run = CFArrayGetValueAtIndex(runArray, runIndex)
            let runb = unsafeBitCast(run, CTRun.self)
            //let runFont:CTFont = CFDictionaryGetValue(CTRunGetAttributes(runb), kCTFontAttributeName as String) as! CTFont
            let CTFontName = unsafeBitCast(kCTFontAttributeName, UnsafePointer<Void>.self)
            let runFontC = CFDictionaryGetValue(CTRunGetAttributes(runb), CTFontName)
            let runFont = unsafeBitCast(runFontC, CTFont.self)

            //for each GLYPH in run
            for runGlyphIndex in 0..<CTRunGetGlyphCount(runb){
                //get Glyph & Glyph-data
                let glyphRange = CFRange(location: runGlyphIndex, length: 1)
                //let glyph:UnsafeMutablePointer<CGGlyph> = UnsafeMutablePointer<CGGlyph>.alloc(1)
                //glyph.initialize(0)
                var glyph:CGGlyph = 0
                let position:UnsafeMutablePointer<CGPoint> = UnsafeMutablePointer<CGPoint>.alloc(1)
                position.initialize(CGPoint.zero)
                CTRunGetGlyphs(runb, glyphRange, &glyph)
                CTRunGetPositions(runb, glyphRange, position)

                //Get PATH of outline
                //let letter = CTFontCreatePathForGlyph(runFont, glyph.memory, nil)
                let letter = CTFontCreatePathForGlyph(runFont, glyph, nil)
                var t = CGAffineTransformMakeTranslation(position.memory.x, position.memory.y)
                //let tx:UnsafeMutablePointer<CGAffineTransform> = UnsafeMutablePointer<CGAffineTransform>.alloc(1)
                //tx.initialize(t)
                CGPathAddPath(letters, &t, letter)
                //CGPathRelease(letter)
                position.destroy()
                position.dealloc(1)
            }
        }

        let path = UIBezierPath()
        path.moveToPoint(CGPoint.zero)
        path.appendPath(UIBezierPath(CGPath: letters))
        return path.CGPath

大家可以对照原来的Obj-c版本看一下,大致都是一一对应的,只有少数几个涉及操作C语言数据的地方有修改,大家可以参考我写的另一篇blog:

Swift中如何转换不同类型的Mutable指针

核心功能有了,下面就好办了!我们想要的是点击屏幕开始显示动画,于是重载如下方法:

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if isAnimating { return }

        isAnimating = true
        flyerLayer.opacity = 0.8

        pathLayer.removeAllAnimations()
        flyerLayer.removeAllAnimations()

        let strokeAnimation = CABasicAnimation(keyPath: "strokeEnd")
        strokeAnimation.duration = 20.0
        strokeAnimation.fromValue = 0.0
        strokeAnimation.toValue = 1.0
        strokeAnimation.delegate = self
        pathLayer.addAnimation(strokeAnimation, forKey: nil)

        let flyAnimation = CAKeyframeAnimation(keyPath: "position")
        flyAnimation.duration = 20.0
        flyAnimation.path = pathLayer.path
        flyAnimation.calculationMode = kCAAnimationPaced

        flyerLayer.addAnimation(flyAnimation, forKey: nil)
    }

下面是App实际运行的效果:

将String转换为其表示的路径画到屏幕上的更多相关文章

  1. C++ 将 std::string 转换为 char*

    参考: std::string to char* C++ 将 std::string 转换为 char* 目前没有直接进行转换的方法.必须通过string对象的c_str()方法,获取C-style的 ...

  2. C#中使用Buffer.BlockCopy()方法将string转换为byte array的方法:

    public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); 将指定数目的字 ...

  3. C++不存在从std::string转换为LPCWSTR的适当函数

    LPCWSTR是什么类型呢? 看看如何定义的: typedef const wchar_t* LPCWSTR; 顾名思义就是: LPCWSTR是一个指向unicode编码字符串的32位指针,所指向字符 ...

  4. string[]转换为int[]

    今天碰到一个问题,要把string[]转换为int[],但是又不想使用循环转换,找了好久最后找到了这种方法,特此记录下. string[] input = { "1", " ...

  5. c#中char、string转换为十六进制byte的浅析

    问题引出: string转换为byte(十六进制) static void Main(string[] args) { "; byte[] b = Encoding.Default.GetB ...

  6. JAVA 利用SimpleDateFormat将String转换为格式化的日期

    1. /** * 使用用户格式提取字符串日期 * * @param strDate 日期字符串 * @param pattern 日期格式 * @return */ public static Dat ...

  7. 【VS开发】ConvertBSTRToString(filename) 不能将string转换为BSTR

    环境:win7,x64,vs2008 sp1 把VC 6.0的工程文件用VS2008打开,编译报错: error C2664:"_com_util::ConvertBSTRToString& ...

  8. (转)第04节:Fabric.js用路径画不规则图形

    在Canvas上画方形.圆形.三角形都是很容易的,只要调用fabric对应的方法就可以了,但这些都是规则的图形,如果你想画一个不规则的图形,这时候你可以用fabric.js提供的路径绘图方法.所谓路径 ...

  9. 有趣html5(两)----使用canvas结合剧本画在画布上的简单图(html5另一个强大)

    请珍惜劳动小编成果,这篇文章是原来小编,转载请注明出处. 于html5中能够使用canvas标签在画布上绘图,先直接上代码,这篇文章先简介一下canvas的用法.简单画几个圆,矩形,三角形,写字. 在 ...

随机推荐

  1. 【Swift】swift中使用kvc赋值的时候,注意事项

    swift中使用kvc赋值的时候.假如给基础数据类型赋值,必须先给基础数据类型的变量一个初始值. 否则将会报错. var setValue(dict["id"], forKey: ...

  2. [Luogu 3674]小清新人渣的本愿

    Description 题库链接 给你一个序列 \(A\) ,长度为 \(n\) ,有 \(m\) 次操作,每次询问一个区间是否可以 选出两个数它们的差为 \(x\) : 选出两个数它们的和为 \(x ...

  3. [AHOI 2016初中组]自行车比赛

    Description 小雪非常关注自行车比赛,尤其是环滨湖自行车赛.一年一度的环滨湖自行车赛,需要选手们连续比赛数日,最终按照累计得分决出冠军.今年一共有 N 位参赛选手.每一天的比赛总会决出当日的 ...

  4. [SCOI2009]windy数

    题目描述 windy定义了一种windy数.不含前导零且相邻两个数字之差至少为2的正整数被称为windy数. windy想知道, 在A和B之间,包括A和B,总共有多少个windy数? 输入输出格式 输 ...

  5. [HEOI2015]小Z的房间

    Description 你突然有了一个大房子,房子里面有一些房间.事实上,你的房子可以看做是一个包含n*m个格子的格状矩形,每个格子是一个房间或者是一个柱子.在一开始的时候,相邻的格子之间都有墙隔着. ...

  6. 【NOIP模拟赛】总结

    题目描述 输入 第一行是5个正整数,n,m,k,S,T,分别代表无向图点数,边数,蝙蝠的数量,二小姐所在起点的编号,目标点的编号. 第二行是k个正整数,分别代表大小姐每个蝙蝠所在的起点的编号.接下来有 ...

  7. HDU2108和HDU2036(叉乘)

    hdu2108 判断是否为凸边形 判断连续三点的叉乘 若为凸,内角<180:若为凹,内角>180 所以通过正负来判断 #include <iostream> #include ...

  8. poj 2417 && poj3243(Baby-Step Giant-Step)

    Discrete Logging Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 4624   Accepted: 2113 ...

  9. quartz问题记录-missed their scheduled fire-time

    这里有3个原因:1.所有的woker thread(工作线程; 辅助线程)都在运行其他的job2.scheduler(调度器)down了(关于这个down.我不太明确是shutdown了..还是挂掉了 ...

  10. Windows系统提供什么样的接口,Unix、Linux系统的用户接口是什么?

    Windows:图形化用户界面 Unix.Linux:独立的环境.