문제

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) and NSStrokeColorAttributeName.


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 and NSStrokeWidthAttributeName.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top