BezierPath曲线 动态绘制文字

直接看代码


- (void)drawTextAnimate {
    
    CAShapeLayer * shapeLayer = [CAShapeLayer layer];
    
    CGSize size = self.view.frame.size;
    CGFloat height = 250;
    
    shapeLayer.frame = CGRectMake(0, (size.height - height)/2, size.width , height);
    shapeLayer.geometryFlipped = YES;
    shapeLayer.strokeColor = [UIColor blackColor].CGColor;
    shapeLayer.fillColor = [UIColor whiteColor].CGColor;;
    shapeLayer.lineWidth = 1;
    shapeLayer.lineJoin = kCALineJoinRound;
    [self.view.layer addSublayer:shapeLayer];
    
    //贝尔兹曲线
    NSString * tempStr = @"动态绘制文字显示";
    
    UIBezierPath *path = [self bezierPathWithText:tempStr attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:30]}];
    shapeLayer.bounds = CGPathGetBoundingBox(path.CGPath);
    shapeLayer.path = path.CGPath;
    
    [shapeLayer removeAllAnimations];
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 0.3f * tempStr.length;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    [shapeLayer addAnimation:pathAnimation forKey:@"strokeEnd"];

}

- (UIBezierPath *)bezierPathWithText:(NSString *)text attributes:(NSDictionary *)attrs {
    
    NSAssert(text!= nil && attrs != nil, @"参数不能为空");

    NSAttributedString * attrStrs = [[NSAttributedString alloc] initWithString:text attributes:attrs];
    CGMutablePathRef paths = CGPathCreateMutable();
    CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)attrStrs);
    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 path = CTFontCreatePathForGlyph(runFont, glyph, NULL);
            CGAffineTransform t = CGAffineTransformMakeTranslation(position.x, position.y);
            CGPathAddPath(paths, &t,path);
            CGPathRelease(path);
        }
    }
    CFRelease(line);
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointZero];
    [path appendPath:[UIBezierPath bezierPathWithCGPath:paths]];
    
    CGPathRelease(paths);
    
    return path;
}

你可能感兴趣的:(BezierPath曲线 动态绘制文字)