我怎样才能画出一个NSString
居中的NSRect
?
我开始时:(来自我的自定义视图的drawRect方法的摘录)
NSString* theString = ... [theString drawInRect:theRect withAttributes:0]; [theString release];
现在我假设我需要设置一些属性.我已经浏览了Apple的Cocoa文档,但它有点压倒性,无法找到任何有关如何向属性添加段落样式的内容.
另外,我只能找到水平对齐,垂直对齐怎么样?
您必须自己进行垂直对齐((视图高度+字符串高度)/ 2).您可以使用水平对齐:
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; style.alignment = NSTextAlignmentCenter; NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName]; [myString drawInRect:someRect withAttributes:attr];
这适用于我的水平对齐
[textX drawInRect:theRect withFont:font lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentCenter];
马丁斯的答案非常接近,但它有一些小错误.试试这个:
NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init]; [style setAlignment:NSCenterTextAlignment]; NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName]; [myString drawInRect:someRect withAttributes:attr]; [style release];
您将不得不创建一个新的NSMutableParagraphStyle
(而不是像Martin建议的那样使用默认的段落样式)因为[NSMutableParagraphStyle defaultParagraphStyle]
返回a NSParagraphStyle
,它没有setAlignment方法.此外,你不需要字符串 - @"NSParagraphStyleAttributeName"
只是NSParagraphStyleAttributeName
.
这对我有用:
CGRect viewRect = CGRectMake(x, y, w, h); UIFont* font = [UIFont systemFontOfSize:15]; CGSize size = [nsText sizeWithFont:font constrainedToSize:viewRect.size lineBreakMode:(UILineBreakModeWordWrap)]; float x_pos = (viewRect.size.width - size.width) / 2; float y_pos = (viewRect.size.height - size.height) /2; [someText drawAtPoint:CGPointMake(viewRect.origin.x + x_pos, viewRect.origin.y + y_pos) withFont:font];