开发者

iPad/iPhone - NSString drawInRect not word wrapping

开发者 https://www.devze.com 2023-01-19 12:48 出处:网络
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\";

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号