2015-12-25 64 views
2

圖紙我目前使用此代碼,以動畫人物的繪製:動畫的信件,CGPaths和CAShapeLayers

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!) 

    } 

(在這種情況下,「J」)創建了一個從性格bezierpath。 Get path to trace out a character in an iOS UIFont

然後我創建一個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) 

結果是我選擇的字符被正確地設置爲動畫。但是,當我添加另一條路徑path.appendPath()附加路徑被添加到原來的路徑正如你所期望的。如果我想繪製所有字符都有適當間距的字母,我該怎麼辦? 謝謝你的時間。

回答

6

您可以使用路徑上的翻譯(使用CGAffineTransformMakeTranslation)執行此操作,因爲路徑沒有「位置」,它只是一組點。但是爲了在角色的每次迭代中進行翻譯,我們需要一個路徑的當前寬度 - 我們可以使用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 
}