我目前正在使用此代码为角色的绘制设置动画:
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").获取跟踪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()
附加路径会被添加到原始路径上,如您所料.如果我想画一个所有字符都有适当间距等的字母,我该怎么办?感谢您的时间.
您可以使用路径上的转换(使用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 }