使用 CoreText 呈现字符串时的字距调整问题
Kerning issue when rendering string using the CoreText
我正在尝试使用 CoreText api 呈现字符串。每个字符都在 CAShapeLayer 中呈现,我正在为每个字符获取层偏移(x 坐标),如下所示:
let offset = CTLineGetOffsetForStringIndex(line, glyphIndex, nil)
但是生成的偏移量似乎不符合字母之间的字距调整。这是我的意思的图像 - 顶部标签是 UILabel,底部是我的自定义渲染:
如您所见,我的自定义标签中的 "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;
}
我正在尝试使用 CoreText api 呈现字符串。每个字符都在 CAShapeLayer 中呈现,我正在为每个字符获取层偏移(x 坐标),如下所示:
let offset = CTLineGetOffsetForStringIndex(line, glyphIndex, nil)
但是生成的偏移量似乎不符合字母之间的字距调整。这是我的意思的图像 - 顶部标签是 UILabel,底部是我的自定义渲染:
如您所见,我的自定义标签中的 "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;
}