Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS UIBezierPath that follows the shape of a font

I am an iOS newbie. How do make I a UIBezierPath that follows an alphabet say "B". The objective is to track touches along this path.

Thanks in advance.

like image 430
user1189363 Avatar asked May 15 '12 11:05

user1189363


1 Answers

CoreText.framework provides methods to get the path of word

see http://www.codeproject.com/Articles/109729/Low-level-text-rendering

code example created by Ole Begemann. Sorry, I forgot download url for the demo named AnimatedPath.

CGMutablePathRef letters = CGPathCreateMutable();

CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica-Bold"), 72.0f, NULL);
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
                       (id)font, kCTFontAttributeName,
                       nil];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"Hello World!"
                                                                 attributes:attrs];
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)attrString);
CFArrayRef runArray = CTLineGetGlyphRuns(line);

// for each RUN
for (CFIndex runIndex = 0; runIndex < CFArrayGetCount(runArray); runIndex++)
{
    // Get FONT for this run
    CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runArray, runIndex);
    CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);

    // for each GLYPH in run
    for (CFIndex runGlyphIndex = 0; runGlyphIndex < CTRunGetGlyphCount(run); runGlyphIndex++) 
    {
        // get Glyph & Glyph-data
        CFRange thisGlyphRange = CFRangeMake(runGlyphIndex, 1);
        CGGlyph glyph;
        CGPoint position;
        CTRunGetGlyphs(run, thisGlyphRange, &glyph);
        CTRunGetPositions(run, thisGlyphRange, &position);

        // Get PATH of outline
        {
            CGPathRef letter = CTFontCreatePathForGlyph(runFont, glyph, NULL);
            CGAffineTransform t = CGAffineTransformMakeTranslation(position.x, position.y);
            CGPathAddPath(letters, &t, letter);
            CGPathRelease(letter);
        }
    }
}
CFRelease(line);

UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointZero];
[path appendPath:[UIBezierPath bezierPathWithCGPath:letters]];

CGPathRelease(letters);
CFRelease(font);

replace “Hello World!” with "The Word you need".

like image 153
nova Avatar answered Sep 23 '22 01:09

nova