ios - 使用 CoreText 呈现字符串时的字距调整问题

标签 ios swift uilabel calayer core-text

我正在尝试使用 CoreText api 呈现字符串。每个字符都在 CAShapeLayer 中呈现,我正在为每个字符获取图层偏移(x 坐标),如下所示:

let offset = CTLineGetOffsetForStringIndex(line, glyphIndex, nil)

但是生成的偏移量似乎不符合字母之间的字距调整。这是我的意思的图像 - 顶部标签是 UILabel,底部是我的自定义渲染:

enter image description here

如您所见,我的自定义标签中的“A”字母离“W”字母更远。

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

最佳答案

万一有人遇到同样的问题,我使用了这个地方的方法:https://github.com/MichMich/XMCircleType/blob/master/XMCircleType/Views/XMCircleTypeView.m , kerningForCharacter 函数。这是函数本身:

- (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;
}

关于ios - 使用 CoreText 呈现字符串时的字距调整问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46941615/

相关文章:

ios - 单击 View 时出现导航栏

objective-c - iOS - 核心数据模型与邮件框架冲突?

python - Swift 与 Python 性能对比

ios - Swift:自动换行不起作用?即使设置

ios - 为什么 UILabel() 返回 nil?

iphone - JSONKit:如何保持 JSON 字典键的顺序

ios - 为什么用于 Feed 发布的 Facebook iOS 对话框在登录后消失?

swift - 如何找出哪个函数卡在主线程上

swift - 在 Observable 数组中搜索一个值

iphone - 更改 UILabel 中的字体名称和粗细(iPhone SDK)