1. 程式人生 > >由文字生成path後制作寫字的動畫

由文字生成path後制作寫字的動畫

rac -m reat mat index release data git ntc

在看以下這個開源組件的時候,發現一個非常棒的方法,能夠將文字生成path,這樣就能夠作出用筆寫字的效果了。 https://github.com/MP0w/MPParallaxCollection
關鍵代碼: -(CGPathRef)pathRefFromText
{
NSAttributedString *attributed = self.attributedText;

CGMutablePathRef letters = CGPathCreateMutable();
CTLineRef line = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)attributed);
CFArrayRef runArray = CTLineGetGlyphRuns(line);
for (CFIndex runIndex = 0; runIndex < CFArrayGetCount(runArray); runIndex++)
{
CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runArray, runIndex);
CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);

for (CFIndex runGlyphIndex = 0; runGlyphIndex < CTRunGetGlyphCount(run); runGlyphIndex++)
{
CFRange thisGlyphRange = CFRangeMake(runGlyphIndex, 1);
CGGlyph glyph;
CGPoint position;
CTRunGetGlyphs(run, thisGlyphRange, &glyph);
CTRunGetPositions(run, thisGlyphRange, &position);

CGPathRef letter = CTFontCreatePathForGlyph(runFont, glyph, NULL);
CGAffineTransform t = CGAffineTransformMakeTranslation(position.x, position.y);
CGPathAddPath(letters, &t, letter);
CGPathRelease(letter);
}
}

UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:letters];
CGRect boundingBox = CGPathGetBoundingBox(letters);
CGPathRelease(letters);
CFRelease(line);


[path applyTransform:CGAffineTransformMakeScale(1.0, -1.0)];
[path applyTransform:CGAffineTransformMakeTranslation(0.0, boundingBox.size.height)];


if (self.reversedAnimation) {
return [[path bezierPathByReversingPath] CGPath];
}

return [path CGPath];
}

由文字生成path後制作寫字的動畫