How can I draw a NSString
centered within a NSRect
?
I've started off with: (an extract from the drawRect method of my custom view)
NSString* theString = ...
[theString drawInRect:theRect withAttributes:0];
[theString release];
Now I'm assuming I need to set up some attributes. I've had a look through Apple's Cocoa documentation, but it's a bit overwhelming and can't find anything for how to add paragraph styles to the attributes.
Also, I can only find horizontal alignment, what about vertical alignment?
Vertical alignment you'll have to do yourself ((height of view + height of string)/2). Horizontal alignment you can do with:
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];
[myString drawInRect:someRect withAttributes:attr];
This works for me for horizontal alignment
[textX drawInRect:theRect
withFont:font
lineBreakMode:UILineBreakModeClip
alignment:UITextAlignmentCenter];
Martins answer is pretty close, but it has a few small errors. Try this:
NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
[style setAlignment:NSCenterTextAlignment];
NSDictionary *attr =
[NSDictionary dictionaryWithObject:style
forKey:NSParagraphStyleAttributeName];
[myString drawInRect:someRect withAttributes:attr];
[style release];
You'll have to create a new NSMutableParagraphStyle
(instead of using the default paragraph style as Martin suggested) because [NSMutableParagraphStyle defaultParagraphStyle]
returns an NSParagraphStyle
, which doesn't have the setAlignment method. Also, you don't need the string @"NSParagraphStyleAttributeName"
—just NSParagraphStyleAttributeName
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With