objective-c - 使用 NSView 在中心显示 NSAttributedString

标签 objective-c cocoa nsview nsattributedstring

我有以下函数来创建属性字符串。

- (NSMutableAttributedString *)makeText:(NSString *)txt : (NSString *)fontname : (CGFloat)tsize :(NSColor *)textColor :(NSColor *)shadowColor :(NSSize)offset {
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowColor = shadowColor;
    shadow.shadowOffset = offset;

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 10.0f;
    paragraphStyle.alignment = NSCenterTextAlignment;

    NSMutableAttributedString *atext = [[NSMutableAttributedString alloc] initWithString:txt];
    NSRange range = NSMakeRange(0,txt.length);

    // alignment
    [atext addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[atext length])];

    ...
    ...
    return atext;
}

如果我将此属性字符串设置为 NSTextField,则生成的属性字符串将正确对齐。但是如果我将它发送到 NSView 的子类,字符串将左对齐。有什么方法可以以正确的对齐方式显示此属性字符串吗?

// .h
@interface imageView1 : NSView {
    NSAttributedString *aStr;
}

// .m
- (void)drawRect:(NSRect)dirtyRect {
    [aStr drawAtPoint:NSMakePoint((self.frame.size.width-aStr.size.width)/2.0f,(self.frame.size.height-aStr.size.height)/2.0f)];
}

感谢您的帮助。操作系统版本为10.8。

最佳答案

如果您在一个点上绘制,则没有与中心相关的边界。您需要指定一个矩形。请参阅docsdrawWithRect:选项:上。请注意其中的警告,指出要中正确选择您的选项,需要(或包含)NSStringDrawingUsesLineFragmentOrigin

关于objective-c - 使用 NSView 在中心显示 NSAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24159777/

相关文章:

macos - CATiledLayer绘制层:inContext always being called on Main thread - MacOS El Capitan

cocoa - 在 NSView 中执行拖放时出现 kCGErrorFailure

objective-c - 屏幕保护程序中的生涩/抖动(核心)动画?

ios - 根据将随机更改的 uilabel.text 的长度设置 UILabel 宽度

objective-c - 使用推送转换交换 NSView

objective-c - 什么时候需要 NSCopying?

objective-c - 更改 MAC 地址 Cocoa - Objective-C

objective-c - 延迟 XCTest 中所有单元测试的执行

ios - 在 UITableViewCell - Objective C 中单击 UiImageView 后如何访问表格单元格

cocoa - NSImage - 裁剪后 PDF 模糊