我正在尝试使用CoreText api渲染字符串。每个字符都在CAShapeLayer中呈现,我得到每个字符的图层偏移量(x坐标),如下所示:
let offset = CTLineGetOffsetForStringIndex(line, glyphIndex, nil)
但结果偏差似乎并不尊重字母之间的字距。这是我的意思的图像 - 顶部标签是UILabel,底部标签是我的自定义渲染:
你可以看到" A"我的自定义标签中的字母放在" W"信件。
我真的很感激任何帮助。 提前谢谢。
答案 0 :(得分:1)
如果有人有同样的问题,我使用了这个地方的方法: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;
}