2010-10-12 18 views
5

我使用以下方法呈現UIView中的某些文本。iPad/iPhone - NSString drawInRect不包含換行

- (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正確計算,但繪製只是渲染一條線。

更新:

已解決。

無論選擇UILineBreak模式如何,設置CGContextSetTextDrawingMode(context, kCGTextFillStrokeClip);都會導致剪輯文本。設置CGContextSetTextDrawingMode(context, kCGTextFillStroke);解決了這個問題。

+1

它工作得很好! – user523234 2013-03-06 18:24:32

回答

0

已解決。

設置CGContextSetTextDrawingMode(context,kCGTextFillStrokeClip);無論選擇了UILineBreak模式,都會導致文本被剪輯。設置CGContextSetTextDrawingMode(context,kCGTextFillStroke);解決了這個問題。

相關問題