我们在看微博时,会看到一些长图片上的显示文章,现在就介绍下如何实现。分析下还是很简单的,总结如下:1、计算文字区域的高 2、利用UIGraphics图形上下文方法来实现 3、验证方法:UIImageWriteToSavedPhotosAlbum,在本地相册中查看成功与否。
-(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();
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
return image;
}