I would like to colour my string and draw it in a rect, my code is
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextDrawingMode(context, kCGTextFillStroke);
CGContextSetRGBStrokeColor(context, 210.0/255.0f, 0.0f, 0.0f, 1.0f);
CGContextSetRGBFillColor(context, 192.0/255.0, 0.0/255.0 , 13.0/255.0, 1.0);
UIFont *font = [UIFont @"MyriadPro-Regular" size:20.0];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
/// Set text alignment
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = @{NSFontAttributeName:font,
NSParagraphStyleAttributeName:paragraphStyle};
NSString *string = @"My code";
[string drawInRect:(isPad)?CGRectMake(1.0, 400.0, 270.0, 120.0):CGRectMake(1.0, 150.0, 125, 120) withAttributes:attributes];
But the corresponding string is not getting the desired colour[which is red]. Are there any attributes missing?
You're working at two different levels here. Setting the fill and stroke color of the CGContext might be appropriate if you were going to use CGContext functions to draw text.
But, since you're using NSAttributedString to draw the text, you need to set the text's fill and stroke colors as attributes.
The attributes you're looking for are
NSForegroundColorAttributeName
(the text fill color) andNSStrokeColorAttributeName
.You also don't need to set the text drawing mode. That, too, is only relevant if you use CGContext functions to draw text.
To get your NSAttributedString stroked, you need to set both
NSStrokeColorAttributeName
andNSStrokeWidthAttributeName
.