Reputation: 51
I am using the DrawRect method to draw some text and can't figure out how to align this text to the right.
I know in interface builder you can specify the alignment so I know it is possible, I just can't seem to figure it out my self.
Any help at this point is extremely helpful.
Thanks so much!
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"AvenirNext-UltraLight" size:12], NSFontAttributeName, [NSColor redColor], NSForegroundColorAttributeName, nil];
NSAttributedString * newEmail = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d", newUnreadEmail] attributes:attributes];
[newEmail drawAtPoint:NSMakePoint(140, 600)];
Upvotes: 2
Views: 1661
Reputation: 24041
if you are using an NSString
class, your life would be easier because you could use the UIStringDrawing
extension of NSString
class with the following methods (you don't need to do any extra thing to use these methods with the NSString
):
- (CGSize)sizeWithFont:(UIFont *)font;
- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode;
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size;
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode;
they give you the exact size of the current string for the selected UIFont
and UILineBreakMode
, and using the size you can count the position on the screen to align the right edge of the string always at the same position.
Upvotes: 2
Reputation: 727137
You need to do math to calculate the correct point for the right alignment. Use [newEmail size]
to calculate the width of the attributed string, subtract it from the width of the rectangle in which you would like it painted, and add the difference to the left coordinate of the point that you pass to the drawAtPoint:
method.
Upvotes: 3