我有以下函数来制作属性字符串。
- (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。
答案 0 :(得分:1)
如果你画一个点,那么就没有与中心相关的界限。你需要指定一个矩形。请参阅drawWithRect:options:
上的docs。请注意那里的警告指出,在中你的选项需要(或包含)NSStringDrawingUsesLineFragmentOrigin
。