如何使用NSString绘制功能从文本创建UIImage [英] How do I use the NSString draw functionality to create a UIImage from text
本文介绍了如何使用NSString绘制功能从文本创建UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 UIImage
中绘制 NSString
变量的内容,但我绝对不知道这个怎么做。我需要编写一个接收 NSString
作为参数的方法,并返回一个带有文本的 UIImage
。
I would like to draw the content of a NSString
variable in a UIImage
, but I have absolutely no idea how to do this. I need to write a method that would receive a NSString
as parameter and return a UIImage
with the text drawn into it.
推荐答案
你可以试试这个:(针对iOS 4更新)
You can try this: (updated for iOS 4)
-(UIImage *)imageFromText:(NSString *)text
{
// set the font type and size
UIFont *font = [UIFont systemFontOfSize:20.0];
CGSize size = [text sizeWithFont:font];
// check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
if (UIGraphicsBeginImageContextWithOptions != NULL)
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
else
// iOS is < 4.0
UIGraphicsBeginImageContext(size);
// optional: add a shadow, to avoid clipping the shadow you should make the context size bigger
//
// CGContextRef ctx = UIGraphicsGetCurrentContext();
// CGContextSetShadowWithColor(ctx, CGSizeMake(1.0, 1.0), 5.0, [[UIColor grayColor] CGColor]);
// draw in context, you can use also drawInRect:withFont:
[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];
// transfer image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
要拨打电话:
UIImage *image = [self imageFromText:@"This is a text"];
这篇关于如何使用NSString绘制功能从文本创建UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文