gpt4 book ai didi

ios - 为什么整个单词的 sizeWithFont 不同于其字母大小的总和?

转载 作者:行者123 更新时间:2023-11-28 19:03:40 27 4
gpt4 key购买 nike

为什么整个单词的 sizeWithFont 会产生与其字母大小之和不同的结果?

以下是带和不带字距调整的文本示例:

CGFloat fontSize = 36;
UIFont *font = [UIFont systemFontOfSize:fontSize];

NSArray *wordsToTest = @[@"IIIIIIIII", @"VAVAVAVAV"];

for (NSString *testWord in wordsToTest) {
CGFloat widthOfTextWithFont = [testWord sizeWithFont:font].width;

CGFloat widthOfTextUsingIteration = 0;
for (int i = 0; i < [testWord length]; i++) {
NSRange range = NSMakeRange(i, 1);
NSString *nextLetter = [testWord substringWithRange:range];

widthOfTextUsingIteration += [nextLetter sizeWithFont:font].width;
}

NSDictionary *attributesKerningDisabled = @{NSFontAttributeName : font,
NSKernAttributeName : @0.0F};
NSAttributedString *attributedStringWithDisabledKerning = [[NSAttributedString alloc] initWithString:testWord attributes:attributesKerningDisabled];


NSDictionary *attributesKerningEnabled = @{NSFontAttributeName : font,
NSKernAttributeName : @1.0F};
NSAttributedString *attributedStringWithEnabledKerning = [[NSAttributedString alloc] initWithString:testWord attributes:attributesKerningEnabled];


NSLog(@"Test for string: %@", testWord);
NSLog(@"Length of the whole word: %f", widthOfTextWithFont);
NSLog(@"Length of word, using iteration: %f", widthOfTextUsingIteration);
NSLog(@"Length of attributed string with enabled kerning: %f", [attributedStringWithEnabledKerning size].width);
NSLog(@"Length of attributed string with disabled kerning: %f", [attributedStringWithDisabledKerning size].width);
}

结果如下:

Test for string: IIIIIIIII
Length of the whole word: 84.000000
Length of word, using iteration: 90.000000
Length of attributed string with enabled kerning: 93.000000
Length of attributed string with disabled kerning: 84.000000

Test for string: VAVAVAVAV
Length of the whole word: 204.000000
Length of word, using iteration: 206.000000
Length of attributed string with enabled kerning: 200.000000
Length of attributed string with disabled kerning: 204.000000

这是 Apple 文档的一部分:

NSKernAttributeName The value of this attribute is an NSNumber object containing a floating-point value. This value specifies the number of points by which to adjust kern-pair characters. Kerning prevents unwanted space from occurring between specific characters and depends on the font. The value 0 means kerning is disabled. The default value for this attribute is 0.

最佳答案

大概是由于字距调整。字距调整是改变连续字母之间的间距以使文本看起来和阅读起来更好的过程。

当您获得完整字符串的大小时,将应用字距调整。对于单个字符,无需紧排,因此可以考虑间距。

( Kerning on wikipedia )


我不相信您对 NSKernAttributeName 的使用会关闭字距调整。我认为在这种情况下使用术语“紧排”是不准确的,它实际上仅指字符之间的额外间距,而不是为字体定义的紧排。

关于ios - 为什么整个单词的 sizeWithFont 不同于其字母大小的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22476201/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com