Ограничивающая рамка символа с диакритическими знаками с помощью CoreText

Я пытаюсь получить ограничивающую рамку символа в MacOS X/iOS, используя различные методы. Я сейчас представляю все свои попытки. До сих пор код терпит неудачу, если я хочу получить размер диакритических знаков, таких как «Ä».

ИспользованиеCTFontGetBoundingRectsForGlyphs

-(void) resizeLayer1:(CATextLayer *)l toString:(NSString *)string
{
    // need to set CGFont explicitly to convert font property to a CGFontRef
    CGFontRef layerFont = CGFontCreateWithFontName((CFStringRef)@"Helvetica");
    l.font = layerFont;

    string = l.string;
    NSUInteger len = [string length];

    // get characters from NSString
    UniChar *characters = (UniChar *)malloc(sizeof(UniChar)*len);
    CFStringGetCharacters((__bridge CFStringRef)l.string, CFRangeMake(0, [l.string length]), characters);

    // Get CTFontRef from CGFontRef
    CTFontRef coreTextFont = CTFontCreateWithGraphicsFont(layerFont, l.fontSize, NULL, NULL);

    // allocate glyphs and bounding box arrays for holding the result
    // assuming that each character is only one glyph, which is wrong
    CGGlyph *glyphs = (CGGlyph *)malloc(sizeof(CGGlyph)*len);
    CTFontGetGlyphsForCharacters(coreTextFont, characters, glyphs, len);

    // get bounding boxes for glyphs
    CGRect *bb = (CGRect *)malloc(sizeof(CGRect)*len);
    CTFontGetBoundingRectsForGlyphs(coreTextFont, kCTFontDefaultOrientation, glyphs, bb, len);
    CFRelease(coreTextFont);

    l.position = CGPointMake(200.f, 100.f);

    l.bounds = bb[0];

    l.backgroundColor = CGColorCreateGenericRGB(0.f,.5f,.9f, 1.f);

    free(characters);
    free(glyphs);
    free(bb);
}

Результат Вроде работает, но происходит некоторое заполнение, поскольку глиф визуализируется CATextLayer

ИспользованиеCTFramesetterSuggestFrameSizeWithConstraints

-(void) resizeLayer2:(CATextLayer *)l toString:(NSString *)string
{
    // need to set CGFont explicitly to convert font property to a CGFontRef
    CGFontRef layerFont = CGFontCreateWithFontName((CFStringRef)@"Helvetica");
    l.font = layerFont;

    string = l.string;

    NSUInteger len = [string length];

    // get characters from NSString
    UniChar *characters = (UniChar *)malloc(sizeof(UniChar)*len);
    CFStringGetCharacters((__bridge CFStringRef)l.string, CFRangeMake(0, [l.string length]), characters);

    // Get CTFontRef from CGFontRef
    CTFontRef coreTextFont = CTFontCreateWithGraphicsFont(layerFont, l.fontSize, NULL, NULL);

    CFMutableAttributedStringRef attrStr = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
    CFAttributedStringReplaceString(attrStr, CFRangeMake(0, 0), (__bridge CFStringRef)string);
    CTTextAlignment alignment = kCTJustifiedTextAlignment;
    CTParagraphStyleSetting _settings[] = { {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment} };
    CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(_settings, sizeof(_settings) / sizeof(_settings[0]));
    CFAttributedStringSetAttribute(attrStr, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTParagraphStyleAttributeName, paragraphStyle);
    CFAttributedStringSetAttribute(attrStr, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTFontAttributeName, coreTextFont);
    CFRelease(paragraphStyle);

    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrStr);
    CFRelease(attrStr);

    CFRange range;
    CGFloat maxWidth  = CGFLOAT_MAX;
    CGFloat maxHeight = 10000.f;
    CGSize constraint = CGSizeMake(maxWidth, maxHeight);

    //  checking frame sizes
    CGSize coreTextSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, len), nil, constraint, &range); 

    // allocate glyphs and bounding box arrays for holding the result
    // assuming that each character is only one glyph, which is wrong
    CGGlyph *glyphs = (CGGlyph *)malloc(sizeof(CGGlyph)*len);
    CTFontGetGlyphsForCharacters(coreTextFont, characters, glyphs, len);

    // get bounding boxes for glyphs
    CGRect *bb = (CGRect *)malloc(sizeof(CGRect)*len);
    CTFontGetBoundingRectsForGlyphs(coreTextFont, kCTFontDefaultOrientation, glyphs, bb, len);
    CFRelease(coreTextFont);

    bb[0].origin = l.bounds.origin;
    coreTextSize.width = ceilf(coreTextSize.width);
    coreTextSize.height = ceilf(coreTextSize.height);
    bb[0].size = coreTextSize;


    l.position = CGPointMake(200.f, 100.f);


    // after setting the bounds the layer gets transparent
    l.bounds = bb[0];
    l.opaque = YES;
    return;    

    l.backgroundColor = CGColorCreateGenericRGB(0.f,.5f,.9f, 1.f);

    free(characters);
    free(glyphs);
    free(bb);
}

Результат Ограничивающий прямоугольник строки правильный. Это становится проблематичным с диакритическими знаками :в Ä отсутствуют точки, потому что ограничивающая рамка недостаточно высока.

ИспользованиеCTLineGetTypographicBounds

-(void) resizeLayer3:(CATextLayer *)l toString:(NSString *)string
{
    // need to set CGFont explicitly to convert font property to a CGFontRef
    CGFontRef layerFont = CGFontCreateWithFontName((CFStringRef)@"Helvetica");
    l.font = layerFont;

    string = l.string;


    NSUInteger len = [string length];

    // get characters from NSString
    UniChar *characters = (UniChar *)malloc(sizeof(UniChar)*len);
    CFStringGetCharacters((__bridge CFStringRef)l.string, CFRangeMake(0, [l.string length]), characters);

    // Get CTFontRef from CGFontRef
    CTFontRef coreTextFont = CTFontCreateWithGraphicsFont(layerFont, l.fontSize, NULL, NULL);

    CFMutableAttributedStringRef attrStr = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
    CFAttributedStringReplaceString(attrStr, CFRangeMake(0, 0), (__bridge CFStringRef)string);
    CFAttributedStringSetAttribute(attrStr, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTFontAttributeName, coreTextFont);

    CTLineRef line = CTLineCreateWithAttributedString(attrStr);
    CGFloat ascent;
    CGFloat descent;
    CGFloat width = CTLineGetTypographicBounds(line, &ascent, &descent, NULL);
    CGFloat height = ascent+descent;
    CGSize coreTextSize = CGSizeMake(width,height);


    // get bounding boxes for glyphs
    CGRect *bb = (CGRect *)malloc(sizeof(CGRect)*len);
    CFRelease(coreTextFont);

    bb[0].origin = CGPointZero;
    coreTextSize.width = ceilf(coreTextSize.width);
    coreTextSize.height = ceilf(coreTextSize.height);
    bb[0].size = coreTextSize;


    l.position = CGPointMake(200.f, 100.f);


    // after setting the bounds the layer gets transparent
    l.bounds = bb[0];
    l.opaque = YES;
    return;    

    l.backgroundColor = CGColorCreateGenericRGB(0.f,.5f,.9f, 1.f);

    free(characters);
    free(bb);
}

Результат Правильная ограничительная рамка строки. Возникают проблемы с диакритическими знаками :в Ä отсутствуют точки, потому что ограничивающая рамка недостаточно высока.

ИспользованиеCTFontGetBoundingRectsForGlyphs

-(void) resizeLayer4:(CATextLayer *)l toString:(NSString *)string
{
    // need to set CGFont explicitly to convert font property to a CGFontRef
    CGFontRef layerFont = CGFontCreateWithFontName((CFStringRef)@"Helvetica");
    l.font = layerFont;

    string = l.string;

    NSUInteger len = [string length];

    // get characters from NSString
    UniChar *characters = (UniChar *)malloc(sizeof(UniChar)*len);
    CFStringGetCharacters((__bridge CFStringRef)l.string, CFRangeMake(0, [l.string length]), characters);

    // Get CTFontRef from CGFontRef
    CTFontRef coreTextFont = CTFontCreateWithGraphicsFont(layerFont, l.fontSize, NULL, NULL);

    // allocate glyphs and bounding box arrays for holding the result
    // assuming that each character is only one glyph, which is wrong
    CGGlyph *glyphs = (CGGlyph *)malloc(sizeof(CGGlyph)*len);
    CTFontGetGlyphsForCharacters(coreTextFont, characters, glyphs, len);

    CGPathRef glyphPath = CTFontCreatePathForGlyph(coreTextFont, glyphs[1], NULL);
    CGRect rect = CGPathGetBoundingBox(glyphPath);

    // get bounding boxes for glyphs
    CGRect *bb = (CGRect *)malloc(sizeof(CGRect)*len);
    CTFontGetBoundingRectsForGlyphs(coreTextFont, kCTFontDefaultOrientation, glyphs, bb, len);
    CFRelease(coreTextFont);

    l.position = CGPointMake(200.f, 100.f);

    l.bounds = rect;

    l.backgroundColor = CGColorCreateGenericRGB(0.f,.5f,.9f, 1.f);

    free(characters);
    free(glyphs);
    free(bb);
}

Результат Ограничивающий прямоугольник строки правильный. С диакритическими знаками возникают проблемы, поскольку сами диакритические знаки являются глифом, а символ - другим глифом, означающим, что Ä состоит из двух глифов. Как это можно использовать?

Есть ли другие возможности, которые я упустил из виду и которые стоит попробовать?

РЕДАКТИРОВАТЬ

Третий вариант CTLineGetTypographicBoundsработает. Однако я столкнулся с другой проблемой: в первой строке в CATextLayerотсутствуют диакритические знаки. Первая строка почему-то просто недостаточно высока. Это означало бы, что я лаю не на то дерево.

8
задан GorillaPatch 10 May 2012 в 21:03
поделиться