Ios 使用CGPATH和CASHAPE图层设置字母图形的动画

Ios 使用CGPATH和CASHAPE图层设置字母图形的动画,ios,swift,uikit,core-animation,cgpath,Ios,Swift,Uikit,Core Animation,Cgpath,我目前正在使用以下代码为角色的绘图设置动画: var path = UIBezierPath() var unichars = [UniChar]("J".utf16) var glyphs = [CGGlyph](count: unichars.count, repeatedValue: 0) let gotGlyphs = CTFontGetGlyphsForCharacters(font, &unichars, &glyphs, unichar

我目前正在使用以下代码为角色的绘图设置动画:

var path = UIBezierPath()


    var unichars = [UniChar]("J".utf16)
    var glyphs = [CGGlyph](count: unichars.count, repeatedValue: 0)

    let gotGlyphs = CTFontGetGlyphsForCharacters(font, &unichars, &glyphs, unichars.count)
    if gotGlyphs {
        let cgpath = CTFontCreatePathForGlyph(font, glyphs[0], nil)
         path = UIBezierPath(CGPath: cgpath!)

    }
从字符创建bezierpath(在本例中为“J”)

然后我创建一个
CAShapeLayer()
,并向其中添加动画

 let layer = CAShapeLayer()
   layer.position = //CGPoint
    layer.bounds = //CGRect()
    view.layer.addSublayer(layer)

    layer.path = path.CGPath

    layer.lineWidth = 5.0
    layer.strokeColor = UIColor.blackColor().CGColor
    layer.fillColor = UIColor.clearColor().CGColor
    layer.geometryFlipped = true

    layer.strokeStart = 0.0
    layer.strokeEnd = 1.0

    let anim = CABasicAnimation(keyPath: "strokeEnd")
    anim.duration = 8.0
    anim.fromValue = 0.0
    anim.toValue = 1.0

    layer.addAnimation(anim, forKey: nil)
结果是我选择的角色被正确地设置动画。但是,当我使用
.appendPath()
将另一个路径添加到
path
时,正如您所期望的那样,追加的路径会直接添加到原始路径上。如果我想画一个所有字符都有适当间距的字母,我该怎么做。?
谢谢您的时间。

您可以使用路径上的翻译(使用
cGraffeTransformMakeTransform
)来完成此操作,因为路径没有“位置”,它只是一组点。但是,要在每个字符的迭代中进行转换,我们需要路径的当前宽度-我们可以使用
CGPathGetBoundingBox()
,这将获得路径将覆盖的框。因此,拥有我们所需要的一切,我们可以做出榜样。为整个单词创建一条路径应该是这样的:

let word = "Test"
let path = UIBezierPath()
let spacing: CGFloat = 50
var i: CGFloat = 0
for letter in word.characters {
    let newPath = getPathForLetter(letter)
    let actualPathRect = CGPathGetBoundingBox(path.CGPath)
    let transform = CGAffineTransformMakeTranslation((CGRectGetWidth(actualPathRect) + min(i, 1)*spacing), 0)
    newPath.applyTransform(transform)
    path.appendPath(newPath)
    i++
}
其中函数
getPathForLetter()
只是:

func getPathForLetter(letter: Character) -> UIBezierPath {
    var path = UIBezierPath()
    let font = CTFontCreateWithName("HelveticaNeue", 64, nil)
    var unichars = [UniChar]("\(letter)".utf16)
    var glyphs = [CGGlyph](count: unichars.count, repeatedValue: 0)

    let gotGlyphs = CTFontGetGlyphsForCharacters(font, &unichars, &glyphs, unichars.count)
    if gotGlyphs {
        let cgpath = CTFontCreatePathForGlyph(font, glyphs[0], nil)
        path = UIBezierPath(CGPath: cgpath!)
    }

    return path
}