Draw center-aligned text in Cocoa View

I am trying to draw a line with new lines (\ n) in cocoa NSView centered. For example, if my line is:

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

I would like it to look like:

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

Here is my code inside the 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];

He still draws the text aligned to the left. What is wrong with this code?

+5
source share
1 answer

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

The width (height for vertical layout) of the rendering area is unlimited, unlike the drawInRect:withAttributes:one that uses the bounding box. As a result, this method displays the text on one line.

, .

-[NSString drawInRect:withAttributes:]. , , . :

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];

, paragraphStyle .

+13

All Articles