开发者

Draw text with center alignment in Cocoa View

I am trying to draw a string with new lines (\n) in a cocoa NSView with center alignment. For example if my string is:

NSString * str = @"this is a long line \n and \n this is also a long line"; 

I would like this to appear somewhat as:

  this is a long line
         and
this is also a long line

Here is my code inside NSView drawRect method:

NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];

[paragraphStyle setAlignment:NSCenterTextAlignment];

NSDictionary * attributes = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName];

NSString * mystr = @"this is a long line \n and \n this is also a long line";

[mystr drawAtPoint:NSMakePoint(20, 20) withAttributes:attributes];

It still draws开发者_如何学编程 the text with left alignment. What is wrong with this code?


The documentation for -[NSString drawAtPoint:withAttributes:] states the following:

The width (height for vertical layout) of the rendering area is unlimited, unlike drawInRect:withAttributes:, which uses a bounding rectangle. As a result, this method renders the text in a single line.

Since the width is unlimited, that method discards paragraph alignment and always renders the string left-aligned.

You should use -[NSString drawInRect:withAttributes:] instead. Since it accepts a frame and a frame has a width, it can compute center alignments. For instance:

NSMutableParagraphStyle * paragraphStyle =
    [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease];
[paragraphStyle setAlignment:NSCenterTextAlignment];
NSDictionary * attributes = [NSDictionary dictionaryWithObject:paragraphStyle
    forKey:NSParagraphStyleAttributeName];

NSString * mystr = @"this is a long line \n and \n this is also a long line";    
NSRect strFrame = { { 20, 20 }, { 200, 200 } };

[mystr drawInRect:strFrame withAttributes:attributes];

Note that you’re leaking paragraphStyle in your original code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜