如何以编程方式将文本保存为Objective-c中的图像文件?

时间:2012-07-20 05:19:35

标签: iphone objective-c image text

我想开发一个项目,我需要通过objective-c将用户输入的文本保存为.PNG文件。我的意思是当用户键入一些文本时,我给用户选择选择字体类型然后保存它。之后,文件将保存为没有背景的.PNG文件。

我怎样才能做到这一点。请分享您的观点。

提前致谢

1 个答案:

答案 0 :(得分:5)

使用此方法从文本中获取图像:

-(UIImage *)imageFromText:(NSString *)text
{
// set the font type and size
//UIFont *font = [UIFont systemFontOfSize:txtView.font];  
CGSize size  = [text sizeWithFont:txtView.font]; // label or textview

// check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
if (UIGraphicsBeginImageContextWithOptions != NULL)
    UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
else
    // iOS is < 4.0 
    UIGraphicsBeginImageContext(size);

 [text drawInRect:CGRectMake(0,0,size.width,size.height) withFont:txtView.font]; 
 UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();    
 return testImg;
}

现在你有像这样的图像保存

NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *pngFilePath = [NSString stringWithFormat:@"%@/test.png",docDir]; // any name u want for image
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)]; your image here
[data1 writeToFile:pngFilePath atomically:YES];