Prat
Prat

Reputation: 505

Converting NSString to NSAttribtuedString for Drawing

I have a string that is being drawn with the code

[@"-" drawInRect: r withFont: f2 lineBreakMode: UILineBreakModeWordWrap alignment: UITextAlignmentCenter];

However I want to change the color in this string, since this is not possible with NSString I wish to modify it to an NSAttributedString.

However this isn't working, here is my modified code, I couldn't find the attributes for the other parameters as well

NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:f2,NSFontAttributeName,
                                        nil];

    NSAttributedString *drawingString = [[NSAttributedString alloc]  initWithString:@"-" attributes:attrsDictionary];

    [drawingString drawInRect:r];

Any Help is appreciated whether this is the right way to do this.

Upvotes: 2

Views: 4406

Answers (2)

Prat
Prat

Reputation: 505

Thanks! Here's my final edited code

    NSMutableParagraphStyle *paraAttr = [[NSMutableParagraphStyle defaultParagraphStyle ] mutableCopy];
    [paraAttr setAlignment:UITextAlignmentCenter];
    [paraAttr setLineBreakMode:UILineBreakModeWordWrap];


    NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:f2,NSFontAttributeName,
                                        [UIColor grayColor],NSForegroundColorAttributeName,
                                        paraAttr,NSParagraphStyleAttributeName,
                                         nil];


    NSAttributedString *drawingString = [[NSAttributedString alloc]  initWithString:@"•" attributes:attrsDictionary];


    [drawingString drawInRect:r];

Upvotes: 2

trojanfoe
trojanfoe

Reputation: 122391

You need to set the NSForegroundColorAttributeName property as well.

Here's a complete list - in the Constants section:

NSString *const NSFontAttributeName;
NSString *const NSParagraphStyleAttributeName;
NSString *const NSForegroundColorAttributeName;
NSString *const NSBackgroundColorAttributeName;
NSString *const NSLigatureAttributeName;
NSString *const NSKernAttributeName;
NSString *const NSStrikethroughStyleAttributeName;
NSString *const NSUnderlineStyleAttributeName;
NSString *const NSStrokeColorAttributeName;
NSString *const NSStrokeWidthAttributeName;
NSString *const NSShadowAttributeName;
NSString *const NSVerticalGlyphFormAttributeName;

Upvotes: 1

Related Questions