代码之家  ›  专栏  ›  技术社区  ›  Nikita Gaidukov

使用CoreText呈现字符串时的紧排问题

  •  0
  • Nikita Gaidukov  · 技术社区  · 8 年前

    我正在尝试使用CoreTextAPI呈现字符串。每个角色都在CAShapeLayer中渲染,我得到每个角色的层偏移(x坐标),如下所示:

    let offset = CTLineGetOffsetForStringIndex(line, glyphIndex, nil)
    

    但由此产生的偏移似乎不尊重字母之间的紧排。这是我的意思的图像-顶部标签是UILabel,底部是我的自定义渲染:

    enter image description here

    如果有任何帮助,我将不胜感激。 提前谢谢。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Nikita Gaidukov    8 年前

    如果有人有同样的问题,我会在这里使用一种方法: https://github.com/MichMich/XMCircleType/blob/master/XMCircleType/Views/XMCircleTypeView.m

    - (float)kerningForCharacter:(NSString *)currentCharacter afterCharacter:(NSString *)previousCharacter
    {
        //Create a unique cache key
        NSString *kerningCacheKey = [NSString stringWithFormat:@"%@%@", previousCharacter, currentCharacter];
    
        //Look for kerning in the cache dictionary
        NSNumber *cachedKerning = [self.kerningCacheDictionary objectForKey:kerningCacheKey];
    
        //If kerning is found: return.
        if (cachedKerning) {
            return [cachedKerning floatValue];
        }
    
        //Otherwise, calculate.
        float totalSize = [[NSString stringWithFormat:@"%@%@", previousCharacter, currentCharacter] sizeWithAttributes:self.textAttributes].width;
        float currentCharacterSize = [currentCharacter sizeWithAttributes:self.textAttributes].width;
        float previousCharacterSize = [previousCharacter sizeWithAttributes:self.textAttributes].width;
    
        float kerning = (currentCharacterSize + previousCharacterSize) - totalSize;
    
        //Store kerning in cache.
        [self.kerningCacheDictionary setValue:@(kerning) forKey:kerningCacheKey];
    
        //Return kerning.
        return kerning;
    }