CGPathRef из строки - PullRequest
       44

CGPathRef из строки

4 голосов
/ 02 апреля 2012

Пожалуйста, как мы можем получить путь конкретного арабского французского письма? Я только что узнал, что CTFontCreatePathForGlyph будет давать CGPathRef как, но это будет контур текста.

Мне нужен этот реальный текстовый путь для отображения анимации рисования текста ..

любая помощь, пожалуйста

Ответы [ 2 ]

10 голосов
/ 03 апреля 2012

Вам вообще не требуется преобразовывать ваш путь в NSString.

Вы можете создать путь для текста следующим образом:

    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);

Так вы создадите путь, для примера кода, пожалуйста, обратитесь к этой ссылке .Этот код является частью этого примера проекта.Надеюсь, это поможет вам

1 голос
/ 06 апреля 2019

Мне нужно было это в Свифте, но было больно тренироваться. Я надеюсь, что это полезно для кого-то еще! Я написал его как расширение для String и NSAttributedString, чтобы сделать его более универсальным.

Вы можете видеть буквы перевернутыми в зависимости от того, как вы рисуете свой путь. Это можно исправить, добавив преобразование вертикального отражения к вызову CTFontCreatePathForGlyph () (вертикальное отражение - это просто CGAffineTransform со шкалой Y, равной -1).

public extension String {
    func path(withFont font: UIFont) -> CGPath {
        let attributedString = NSAttributedString(string: self, attributes: [.font: font])
        let path = attributedString.path()
        return path
    }
}

public extension NSAttributedString {
    func path() -> CGPath {
        let path = CGMutablePath()

        // Use CoreText to lay the string out as a line
        let line = CTLineCreateWithAttributedString(self as CFAttributedString)

        // Iterate the runs on the line
        let runArray = CTLineGetGlyphRuns(line)
        let numRuns = CFArrayGetCount(runArray)
        for runIndex in 0..<numRuns {

            // Get the font for this run
            let run = unsafeBitCast(CFArrayGetValueAtIndex(runArray, runIndex), to: CTRun.self)
            let runAttributes = CTRunGetAttributes(run) as Dictionary
            let runFont = runAttributes[kCTFontAttributeName] as! CTFont

            // Iterate the glyphs in this run
            let numGlyphs = CTRunGetGlyphCount(run)
            for glyphIndex in 0..<numGlyphs {
                let glyphRange = CFRangeMake(glyphIndex, 1)

                // Get the glyph
                var glyph : CGGlyph = 0
                withUnsafeMutablePointer(to: &glyph) { glyphPtr in
                    CTRunGetGlyphs(run, glyphRange, glyphPtr)
                }

                // Get the position
                var position : CGPoint = .zero
                withUnsafeMutablePointer(to: &position) {positionPtr in
                    CTRunGetPositions(run, glyphRange, positionPtr)
                }

                // Get a path for the glyph
                guard let glyphPath = CTFontCreatePathForGlyph(runFont, glyph, nil) else {
                    continue
                }

                // Transform the glyph as it is added to the final path
                let t = CGAffineTransform(translationX: position.x, y: position.y)
                path.addPath(glyphPath, transform: t)
            }
        }

        return path
    }
}
...