【发布时间】:2014-04-23 22:43:53
【问题描述】:
为什么整个单词的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 该属性的值是一个包含浮点值的 NSNumber 对象。此值指定调整紧缩对字符的点数。字距调整可防止特定字符之间出现不需要的空间,并且取决于字体。值 0 表示禁用字距调整。此属性的默认值为 0。
【问题讨论】:
标签: ios objective-c nsstring uifont