iPad/iPhone - NSString drawInRect not word wrapping
I'm using the following to render some text in a UIView
.
- (void) drawRect:(CGRect)rect
{
NSString* text = @"asdf asdf asdf asdf asdf asdf asdf";
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
CGContextFillRect(context, rect);
CGContextSetTextDrawingMode(context, kCGTextFillStrokeClip);
CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColo开发者_Python百科r]);
CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]);
CGContextSetShouldSmoothFonts(context, YES);
UIFont* font = [UIFont fontWithName:@"ArialRoundedMTBold" size:20.0f];
CGSize textMaxSize = CGSizeMake(rect.size.width - 20.0f, rect.size.height);
CGSize textSize = [text sizeWithFont:font constrainedToSize:textMaxSize lineBreakMode:UILineBreakModeWordWrap];
CGRect textRect = CGRectMake(10.0f, 10.0f, textSize.width, textSize.height);
[text drawInRect:textRect withFont:font];
[text drawInRect:textRect withFont:font lineBreakMode:UILineBreakModeWordWrap];
[text drawInRect:textRect withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentCenter];
}
None of the [text drawInRect]
's wrap the text like I expect. TextSize
is computed properly but the draw is just rendering a single line.
Update:
Solved.
Settings CGContextSetTextDrawingMode(context, kCGTextFillStrokeClip);
will cause the text to clip regardless of UILineBreak
mode selected. Setting CGContextSetTextDrawingMode(context, kCGTextFillStroke);
solved this issue.
Its possible you don't have the vertical size in your textRect. Check out this similar question:
How do I get -[NSString sizeWithFont:forWidth:lineBreakMode:] to work?
Solved.
Settings CGContextSetTextDrawingMode(context, kCGTextFillStrokeClip); will cause the text to clip regardless of UILineBreak mode selected. Setting CGContextSetTextDrawingMode(context, kCGTextFillStroke); solved this issue.
精彩评论