将文字导出为.png .jpg .pdf 的文件
2016-10-20 本文已影响0人
梦之志
- 将将NSString类型转成UIImage类型
#pragma 将文字转成图片
+(UIImage *)imageFromText:(NSArray *)arrContent withFont:(CGFloat)fontSize{
// arrContent为字符数组
UIFont * font = [UIFont systemFontOfSize:fontSize];
NSMutableArray * arrHeight = [[NSMutableArray alloc]initWithCapacity:arrContent.count];
CGFloat fHeight = 0.0f;
//计算文字的长度
for (NSString * sContent in arrContent) {
CGSize size = CGSizeMake(320, MAXFLOAT);
NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];
size = [sContent boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
[arrHeight addObject:[NSNumber numberWithFloat:size.height]];
fHeight += size.height;
}
CGSize newSize = CGSizeMake(320+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, 320 , [numHeight floatValue]);
[sContent drawInRect:rect withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
fPosY += [numHeight floatValue];
nIndex++;
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
2.将 UIImage 类型 写入 文件(.png 或 ,jpg)
#pragma 将UIImage写入文件
+(BOOL)WriteImage:(UIImage *)image toFileAtPath:(NSString *)aPath{
if ((image == nil) || (aPath == nil) || ([aPath isEqualToString:@""])){
return NO;
}
@try {
NSData * imageData = nil;
NSString * ext = [aPath pathExtension];
if ([ext isEqualToString:@"png"]) {
imageData = UIImagePNGRepresentation(image);
}else{
imageData = UIImageJPEGRepresentation(image, 0);
}
if ((imageData == nil) || ([imageData length] <= 0)) {
return NO;
}
[imageData writeToFile:aPath atomically:YES];
return YES;
} @catch (NSException *exception) {
NSLog(@"%@",exception);
} @finally {
}
}
3.将 UIView 类型 转 PDF 文件
#pragma mark - View转PDF文件
+(BOOL)CreatPDFFromUIView:(UIView *)View aPath:(NSString *)path{
BOOL res;
NSMutableData * pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData,(CGRect){0,0,View.frame.size},nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0,0,View.frame.size.width,View.frame.size.height),nil);
CGContextRef pdfContext=UIGraphicsGetCurrentContext();
CGRect origSize = View.frame;
CGRect newSize = origSize;
newSize.size = View.frame.size;
[View setFrame:newSize];
[View.layer renderInContext:pdfContext];
[View setFrame:origSize];
UIGraphicsEndPDFContext();
//将数据转成写入文件
res = [pdfData writeToFile:path atomically:YES];
return res;
}