我需要为使用多种字体的选定富文本设置文本大小(例如设置为 42)。
我想我可以检查每组字符的属性,修改字体大小并重新设置属性,但是看着浮动的字体面板,似乎应该有一种非常简单直接的方法来实现这一点。我错过了一些明显的东西吗?
我需要为使用多种字体的选定富文本设置文本大小(例如设置为 42)。
我想我可以检查每组字符的属性,修改字体大小并重新设置属性,但是看着浮动的字体面板,似乎应该有一种非常简单直接的方法来实现这一点。我错过了一些明显的东西吗?
在 10.6 上,有一种方便的方法可以迭代属性并增加字体大小。此方法可以添加到 NSTextView 类别中。
- (IBAction)increaseFontSize:(id)sender
{
NSTextStorage *textStorage = [self textStorage];
[textStorage beginEditing];
[textStorage enumerateAttributesInRange: NSMakeRange(0, [textStorage length])
options: 0
usingBlock: ^(NSDictionary *attributesDictionary,
NSRange range,
BOOL *stop)
{
#pragma unused(stop)
NSFont *font = [attributesDictionary objectForKey:NSFontAttributeName];
if (font) {
[textStorage removeAttribute:NSFontAttributeName range:range];
font = [[NSFontManager sharedFontManager] convertFont:font toSize:[font pointSize] + 1];
[textStorage addAttribute:NSFontAttributeName value:font range:range];
}
}];
[textStorage endEditing];
[self didChangeText];
}
概括一下乔纳森的回答,这是一个类别界面,您可以简单地将其粘贴到 Xcode 项目中的适当文件中:
@interface NSTextView (FrameworkAdditions)
- (IBAction)decrementFontSize:(id)sender;
- (IBAction)incrementFontSize:(id)sender;
@end
以及相应的实现:
@implementation NSTextView (FrameworkAdditions)
- (void)changeFontSize:(CGFloat)delta;
{
NSFontManager * fontManager = [NSFontManager sharedFontManager];
NSTextStorage * textStorage = [self textStorage];
[textStorage beginEditing];
[textStorage enumerateAttribute:NSFontAttributeName
inRange:NSMakeRange(0, [textStorage length])
options:0
usingBlock:^(id value,
NSRange range,
BOOL * stop)
{
NSFont * font = value;
font = [fontManager convertFont:font
toSize:[font pointSize] + delta];
if (font != nil) {
[textStorage removeAttribute:NSFontAttributeName
range:range];
[textStorage addAttribute:NSFontAttributeName
value:font
range:range];
}
}];
[textStorage endEditing];
[self didChangeText];
}
- (IBAction)decrementFontSize:(id)sender;
{
[self changeFontSize:-1.0];
}
- (IBAction)incrementFontSize:(id)sender;
{
[self changeFontSize:1.0];
}
@end
这将使字体大小加倍,但您可以将 scale 属性更改为任何值,或提供固定大小
NSFont * font = ...;
CGFloat fontSize = [[font fontDescriptor].fontAttributes[NSFontSizeAttribute] floatValue];
font = [NSFont fontWithDescriptor:[font fontDescriptor] size:fontSize * 2.];
self.textField.font = font;
注意:我假设您使用的是 NSTextView 并且您可以访问它的文本存储(NSTextStorage)。
我认为不可能只在使用多种字体的文本上更改字体大小。在 NSAttributedString 中,字体的大小是 NSFontAttributeName 属性的一部分,该属性控制字体和大小。
一种解决方案是迭代选择并在attribute:atIndex:longestEffectiveRange:inRange:
应用每种字体时使用 来捕获范围,更改字体大小,然后使用addAttribute:value:range:
来在范围内设置新字体。
更新:
如果您查看NSTextView(在 LGPL 下)的 GNUstep GUI 源代码,您会发现它们的实现使用了范围迭代。
由于NSTextView
是 的子类NSView
,您可以使用它-scaleUnitSquareToSize:
来更改文本视图的放大级别。例如,要使您调用的所有文本变大:
[textView scaleUnitSquareToSize:NSMakeSize(2.0, 2.0)];
执行此操作后,您可能需要对文本视图的尺寸进行一些调整,NSTextContainer
以确保文本布局正确。