试试这个:
-(void)drawText:(NSString *)string {
// this method must be called after a valid graphic context
// is configured, it can be called in drawRect:, or a bitmap or pdf context is configured.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
myFontForContentBold, NSFontAttributeName,
[NSNumber numberWithFloat:1.0], NSBaselineOffsetAttributeName, nil];
NSAttributedString *richText = [[NSAttributedString alloc] initWithString:string attributes:attrsDictionary];
CGRect textRect = [richText boundingRectWithSize:CGSizeMake(400, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
context:nil];
textRect = CGRectMake(130, 80, 400, textRect.size.height);
[richText drawInRect:textRect];
}
如果您需要绘制大量文本,请考虑Text Kit
.
Text Kit
方法:
- (void)drawAddressList:(NSArray *)list atPoint:(CGPoint)point {
NSTextStorage *textStorage = [[NSTextStorage alloc] init];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(400.0f, FLT_MAX)];
[textStorage addLayoutManager:layoutManager];
[layoutManager addTextContainer:textContainer];
textContainer.lineFragmentPadding = 0.0f;
NSDictionary *attributes = @{NSFontAttributeName:[UIFont preferredFontForTextStyle:UIFontTextStyleBody]};
// it's a simple attributes for illustration
for (NSString *address in list) {
NSString *buffer = [NSString stringWithFormat:@"%@\n", address];
[textStorage appendAttributedString:[[NSAttributedString alloc] initWithString:buffer attributes:attributes]];
}
[layoutManager ensureLayoutForTextContainer:textContainer];
CGRect rect = [layoutManager usedRectForTextContainer:textContainer];
rect.size.width = 400.0f;
rect.size.height = ceilf(rect.size.height);
rect.origin = point; // this is the frame needed to draw the address list
[layoutManager drawGlyphsForGlyphRange:NSMakeRange(0, textStorage.length) atPoint:point];
}