Skip to content

Instantly share code, notes, and snippets.

@webfrogs
Created April 6, 2015 07:09
Show Gist options
  • Save webfrogs/dc49f3c0991f83c2fe2a to your computer and use it in GitHub Desktop.
Save webfrogs/dc49f3c0991f83c2fe2a to your computer and use it in GitHub Desktop.
letter path animation
let letters = CGPathCreateMutable()
let font = CTFontCreateWithName("Helvetica-Bold", 72, nil)
let attrs: [String: AnyObject] = [kCTFontAttributeName: font]
let attrString = NSAttributedString(string: "~", attributes: attrs)
let line = CTLineCreateWithAttributedString(attrString)
let runArray = CTLineGetGlyphRuns(line)
for index in 0 ..< CFArrayGetCount(runArray){
let run = unsafeBitCast(CFArrayGetValueAtIndex(runArray, index), CTRunRef.self)
let runFont = unsafeBitCast(CFDictionaryGetValue(CTRunGetAttributes(run), unsafeBitCast(kCTFontAttributeName, UnsafePointer<Void>.self)), CTFontRef.self)
for runGlyphIndex in 0 ..< CTRunGetGlyphCount(run){
let thisGlyphRange = CFRangeMake(runGlyphIndex, 1)
var glyph: CGGlyph = CGGlyph()
var position: CGPoint = CGPoint()
CTRunGetGlyphs(run, thisGlyphRange, &glyph)
CTRunGetPositions(run, thisGlyphRange, &position)
let letter = CTFontCreatePathForGlyph(runFont, glyph, nil)
var t = CGAffineTransformMakeTranslation(position.x, position.y)
CGPathAddPath(letters, &t, letter)
}
}
let shapeLayer = CAShapeLayer()
shapeLayer.path = letters
let screenSize = UIScreen.mainScreen().bounds
shapeLayer.frame = CGRect(x: (screenSize.width-attrString.size().width)/2,
y: (screenSize.height-attrString.size().height)/2,
width: attrString.size().width,
height: attrString.size().height)
shapeLayer.strokeColor = UIColor.blackColor().CGColor
shapeLayer.fillColor = nil
shapeLayer.lineWidth = 3.0
shapeLayer.geometryFlipped = true // 上下翻转 ShapeLayer 的坐标系
view.layer.addSublayer(shapeLayer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment