How to set text color when using drawInRect?
Asked Answered
H

1

8

I have been using PaintCode to draw some of the graphics within my app, some of the drawn elements have text that is drawn using "drawInRect". The text is always showing up black regardless of what I do to try and set the color.

here is the code where the text is created, and I am attempting to set the color:

       //// Rounded Rectangle Drawing
    UIBezierPath* roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, 66, 66) cornerRadius: 15];
    [[NPSColor NPSPrimaryColor] setFill];
    [roundedRectanglePath fill];

    UIFont *helveticaFont = [UIFont fontWithName:@"AvenirNextCondensed-Bold" size:50];

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    /// Set line break mode
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    /// Set text alignment
    paragraphStyle.alignment = NSTextAlignmentCenter;

    NSDictionary *attributes = @{NSFontAttributeName:helveticaFont,
                                 NSParagraphStyleAttributeName:paragraphStyle};


    //// Text Drawing
    CGRect textRect = CGRectMake(-4, -2.5, 74, 71.5);
    [[NPSColor whiteColor] set];
    [textContent drawInRect: CGRectInset(textRect, 0, 6) withAttributes:attributes];

}

The white color in the "text drawing" is what is not working properly. Thanks for the assistance.

Heft answered 15/2, 2014 at 22:15 Comment(3)
Update your attributes to include the color.Luxembourg
What's a "NPSColor"? What happens if you try something like "[[UIColor redColor] set];" before drawing the text? Does it come out red?Aromatic
NPSColor is a custom category of UIColor ...Heft
A
19

You need to set the color of the text in the "attributes" dictionary you pass in via:

[textContent drawInRect: CGRectInset(textRect, 0, 6) withAttributes:attributes];

My suggest would be:

NSDictionary *attributes = @{ NSFontAttributeName:helveticaFont,
                              NSParagraphStyleAttributeName:paragraphStyle,
                              NSForegroundColorAttributeName: [NPSColor whiteColor]}
Aromatic answered 15/2, 2014 at 22:21 Comment(2)
Yep that was it,I was having a hard time finding the right "NSAttribute" I tried Color, text color, font color ...I never tried "NSFore...." Thank you !Heft
is it possible to apply gradient color to text with attributes using draw in rect in swift? you can check question also if possible: #67807862Bloodshot

© 2022 - 2024 — McMap. All rights reserved.