我目前正在使用此代码为角色的绘制设置动画:
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"在这种情况下)。 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()
添加另一条路径时,会将附加路径添加到原始路径上,如您所料。如果我想画一个所有字符都有适当间距等的字母,我该怎么办?
谢谢你的时间。
答案 0 :(得分:6)
You can do this using translation on path (using CGAffineTransformMakeTranslation
), since path doesn't have a "position", it is just set of points. But to make a translation every iteration of a character, we need a current width of a path - we can use CGPathGetBoundingBox()
for this, which gets the box that the path will cover. So having everything we need, we can make an example. Make a path for whole word would be something along the lines:
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++
}
Where function getPathForLetter()
is just:
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
}