【发布时间】:2019-03-01 16:07:30
【问题描述】:
我需要使用Kern attribute 或NSAttributedString。正如我在文档中看到的那样,该属性的默认值为 0.0。但是我遇到了短语Hello, world 的奇怪行为(对于短语“Hello”,一切都很好):
NSDictionary<NSString*, id>* attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:12]};
NSString* text = @"Hello, World";
NSAttributedString* string = [[NSAttributedString alloc] initWithString:text attributes:attributes];
CGSize size1 = [string size];
NSMutableDictionary<NSString*, id>* attributesWithKernel = [attributes mutableCopy];
attributesWithKernel[NSKernAttributeName] = @(0.0);
NSAttributedString* stringWithKern = [[NSAttributedString alloc] initWithString:text attributes:attributesWithKernel];
CGSize size2 = [stringWithKern size];
XCTAssertTrue(CGSizeEqualToSize(size1, size2)); //here test falls
//size1 = size1 = (width = 68.8125, height = 14.3203125)
//size2 = (width = 69.515625, height = 14.3203125)
要使 size1 和 size2 相等,字距应该相等 -7.105427357601002e-15 ,我知道这非常接近 0.0,但很奇怪,因为这会改变几乎一个像素的宽度。NSAttributedString 具有相同的Objective-C 和 Swift 中的行为,例如 swift:
let text = "Hello, World"
let attributes : [NSAttributedString.Key : Any] = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: UIFont.systemFontSize)]
let str = NSAttributedString(string: text, attributes: attributes)
let size = str.size()
var attributesWithKern = attributes
attributesWithKern[NSAttributedString.Key.kern] = NSNumber(value: 0.0)
let strWithKern = NSAttributedString(string: text, attributes: attributesWithKern)
let sizeWithKern = strWithKern.size()
XCTAssertTrue(size == sizeWithKern)
我该如何解决这种行为?
附言
现在,如果键等于 0.0,我只需从属性字符串中删除 NSKernAttributeKey,但我认为这不是一个好的解决方案。
【问题讨论】:
-
This question about different result of size method for attributes with and without default value for kerning.
标签: ios objective-c swift nsattributedstring kerning