【问题标题】:Custom font misplaced in Cocoa自定义字体在 Cocoa 中错位
【发布时间】:2014-04-25 22:29:30
【问题描述】:
【问题讨论】:
标签:
objective-c
cocoa
fonts
【解决方案1】:
这对于“Helvetica Neue”来说尤其糟糕,它是一种标准字体(在 iOS 中),并且可能在未来的 OS X 版本中发挥更大的作用。除了更改字体之外,我不知道调整单个控件的方法,但我找到了一种通过自己的计算正确呈现文本的方法。这里的关键是不要使用字符串高度(例如,用于居中或放置字符串),而是要考虑升序和 xHeight。
以下代码绘制垂直居中的 NSTextFieldCell 的标题,与使用的字体无关:
- (NSRect)titleRectForBounds: (NSRect)theRect
{
NSRect titleFrame = [super titleRectForBounds: theRect];
CGRect rect = [self.attributedStringValue boundingRectWithSize: NSMakeSize(FLT_MAX, NSHeight(titleFrame))
options: 0];
titleFrame.origin.y -= NSHeight(rect) - floor(self.font.ascender);
titleFrame.origin.y += floor((titleFrame.size.height - self.font.xHeight) / 2);
return titleFrame;
}
- (void)drawInteriorWithFrame: (NSRect)cellFrame inView: (NSView *)controlView
{
NSRect titleRect = [self titleRectForBounds: cellFrame];
[self.attributedStringValue drawInRect: titleRect];
}
单元格是 NSOutlineView 的一部分,因此被翻转。对于非翻转内容,解决方案可能更简单一些(尚未测试)。
【解决方案2】:
使用 NSButtonCell 类的 setAttributedTitle:。
提供一个 NSAttributedString
有关指导,请参阅属性字符串编程指南。该字体将是定义文本样式的 NSMutableParagraphStyle 的一部分。
标准按钮使用预定义的样式来完成所有这些工作。