由于在应用中有分享微博功能,文字较长时需要截断,导致不完整,所以必须自动转成图片,发长微博来解决问题。先将方法分享如下,以下方法经过实际应用,没有问题。
#define CONTENT_MAX_WIDTH 300.0f
+(UIImage *)imageFromText:(NSArray*) arrContent withFont: (CGFloat)fontSize
{
// set the font type and size
UIFont *font = [UIFont systemFontOfSize:fontSize];
NSMutableArray *arrHeight = [[NSMutableArray alloc] initWithCapacity:arrContent.count];
CGFloat fHeight = 0.0f;
for (NSString *sContent in arrContent) {
CGSize stringSize = [sContent sizeWithFont:font constrainedToSize:CGSizeMake(CONTENT_MAX_WIDTH, 10000) lineBreakMode:UILineBreakModeWordWrap];
[arrHeight addObject:[NSNumber numberWithFloat:stringSize.height]];
fHeight += stringSize.height;
}
CGSize newSize = CGSizeMake(CONTENT_MAX_WIDTH+20, fHeight+50);
UIGraphicsBeginImageContextWithOptions(newSize,NO,0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetCharacterSpacing(ctx, 10);
CGContextSetTextDrawingMode (ctx, kCGTextFillStroke);
CGContextSetRGBFillColor (ctx, 0.1, 0.2, 0.3, 1); // 6
CGContextSetRGBStrokeColor (ctx, 0, 0, 0, 1);
int nIndex = 0;
CGFloat fPosY = 20.0f;
for (NSString *sContent in arrContent) {
NSNumber *numHeight = [arrHeight objectAtIndex:nIndex];
CGRect rect = CGRectMake(10, fPosY, CONTENT_MAX_WIDTH , [numHeight floatValue]);
[sContent drawInRect:rect withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
fPosY += [numHeight floatValue];
nIndex++;
}
// transfer image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[arrHeight release];
return image;
}
ps:参数为什么要用NSArray?由于大段文字里面有各种语言,有些语言需要从右向左显示,所以在程序处理时可以进行判断,然后进行处理。为简化程序,本人将该部分代码删除掉了。