iPad / iPhone - NSString drawInRect没有自动换行

时间:2010-10-12 14:48:41

标签: iphone ipad ios4 nsstring

我正在使用以下内容在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] CGColor]);

    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];
}

[text drawInRect]没有像我期望的那样包装文本。 TextSize计算正确但绘制只是渲染一行。

更新

解决。

设置CGContextSetTextDrawingMode(context, kCGTextFillStrokeClip);将导致文本剪辑,无论选择UILineBreak模式。设置CGContextSetTextDrawingMode(context, kCGTextFillStroke);解决了这个问题。

2 个答案:

答案 0 :(得分:0)

你可能没有textRect中的垂直大小。看看这个类似的问题:

How do I get -[NSString sizeWithFont:forWidth:lineBreakMode:] to work?

答案 1 :(得分:0)

解决。

设置CGContextSetTextDrawingMode(context,kCGTextFillStrokeClip);无论选择何种UILineBreak模式,都会导致文本剪辑。设置CGContextSetTextDrawingMode(context,kCGTextFillStroke);解决了这个问题。